Announcement

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

  • Replace variable value with another variable's name

    Hi,

    My dataset is of the form:
    XVAR Spain France UK Germany relevant_country
    1 1 . . . Spain
    3 . 3 . . France
    5 . . 5 . UK
    7 . . . 7 Germany

    Except that I do not have the variable relevant_country, which I am trying to create. This variable should taked the value of "Spain" if XVAR's value comes from the variable Spain, and the same for the other countries.

    I have tried to do the following:

    Code:
    global countries Spain France UK Germany
    
    gen relevant_country=.
    
    foreach cntry in $countries{
    
    global outcome "cntry'"
    
    replace relevant_country=$outcome if country!=.
    
    }
    However, instead of the variable containing the country names, it contains the country values (so is identical to XVAR). How can I tell Stata to take the variable name instead of the variable value?

    Thank you very much!






  • #2
    Code:
    clear 
    input XVAR    Spain    France    UK    Germany    str42 relevant_country
    1    1    .    .    .    "Spain"
    3    .    3    .    .    "France"
    5    .    .    5    .    "UK"
    7    .    .    .    7    "Germany"
    end 
    
    gen wanted = "" 
    
    foreach c of varlist Spain-Germany { 
        replace wanted = "`c'" if `c' < .     
    }
    
    list
    No need for any globals.

    Comment


    • #3
      This works, thanks a lot!

      Comment

      Working...
      X