Announcement

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

  • If an item in a list matches the name of a variable, replace the value of that variable with 1

    Hi all - I have a string variable that has a list of various possible moods. I'm hoping to be able to work through that list and if a word on that list matches a variable name, code that variable 1 for that observation. I already generated the full list of variables using:

    Code:
    levelsof update_pledge_mood1, local(moods)
    
    foreach l of local moods {
        gen `l' = . 
    }
    So, just could use some help with the next steps.

    Here's the structure:

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str15 update_pledge_mood1 float(angry annoyed appreciated content exhausted unmotivated)
    "content"     . . . . . .
    "angry"       . . . . . .
    ""            . . . . . .
    "unmotivated" . . . . . .
    "exhausted"   . . . . . .
    "content"     . . . . . .
    "appreciated" . . . . . .
    end
    And here's what I'm trying to achieve:


    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str15 update_pledge_mood1 float(angry annoyed appreciated content exhausted unmotivated)
    "content"     . . . 1 . .
    "angry"       1 . . . . .
    ""            . . . . . .
    "unmotivated" . . . . . 1
    "exhausted"   . . . . 1 .
    "content"     . . . 1 . .
    "appreciated" . . 1 . . .
    end

  • #2
    This is almost what you asked for:
    Code:
    foreach v of varlist angry-unmotivated {
        replace `v' = (update_pledge_mood1) == "`v'"
    }
    The difference is that instead of missing values, there are zeroes where things don't match. If you really want the missing values you can always replace the zeroes with missing values. But really you shouldn't do that: in Stata, coding variables as 1/. instead of 1/0 is just a recipe for trouble and usually leads to bad results down the line. You will almost certainly be better off with zeroes.

    Comment


    • #3
      That's perfect! Definitely doesn't need to be missing, zeros are perfectly fine. Thanks so much for your help, as usual!

      Comment

      Working...
      X