Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to replace string values for a variable with numeric values (not labels).

    I have a string variable 'businessincome' such as:

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str68 businessincome
    ""  
    ""  
    ""  
    ""  
    ""  
    ""  
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    "10"
    end
    Now, I want to replace "11" with the numeric (not label) value 1, "4" with 2, "6" with 3 and "8" with 4, "10" with 5, and "12" as missing.

    Thanks
    Last edited by anisha arya; 09 Aug 2024, 15:41.

  • #2
    Code:
    gen wanted = _n
    may help.

    Comment


    • #3
      There is no single official Stata command that will replace a string variable with numbers. So you have to create a new variable. Then you can drop the original and rename the new one to the original's name. There are several simple ways to create the new variable. Here's one.
      Code:
      label define junk    1 "11"    ///
                          2 "4"    ///
                          3 "6"    ///
                          4 "8"    ///
                          5 "10"    ///
                          .a "12"
      encode businessincome, gen(wanted) label(junk)
      replace wanted = . if wanted == .a
      label drop junk

      Comment


      • #4
        Re #2. I don't see how that advice applies to the question posed. What am I missing?

        Comment


        • #5
          #2 was an answer to the original version of #1 which was quite different.
          Last edited by Nick Cox; 09 Aug 2024, 19:18.

          Comment

          Working...
          X