Announcement

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

  • generating variable containing value of variable referenced in another variable

    I have dataset with a variable (refvar) that references, as values, the names of other variables in the dataset. I wish to generate a new variable (newvar) that outputs the value of the variable being referenced. As an example:
    obs aaa bbb ccc ddd eee refvar newvar
    1 9 5 4.3 6 7 bbb 5
    2 1 7 1 1 6 ccc 1
    3 6.8 2 7 3 4 aaa 6.8
    4 1 1 9 5 2 bbb 1
    Not sure how to go about creating newvar.
    Last edited by michael joe; 12 Jun 2018, 05:15.

  • #2
    Here's one approach that works with your data.
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input byte obs float aaa byte bbb float ccc byte(ddd eee) str3 refvar float newvar
    1   9 5 4.3 6 7 "bbb"   5
    2   1 7   1 1 6 "ccc"   1
    3 6.8 2   7 3 4 "aaa" 6.8
    4   1 1   9 5 2 "bbb"   1
    end
    generate newvar2 = .
    foreach var of varlist aaa-eee {
        replace newvar2 = `var' if "`var'"==refvar
        }
    Code:
    . list, clean noobs
    
        obs   aaa   bbb   ccc   ddd   eee   refvar   newvar   newvar2  
          1     9     5   4.3     6     7      bbb        5         5  
          2     1     7     1     1     6      ccc        1         1  
          3   6.8     2     7     3     4      aaa      6.8       6.8  
          4     1     1     9     5     2      bbb        1         1
    With that said, please review the Statalist FAQ linked to from the top of the page, as well as from the Advice on Posting link on the page you used to create your post, looking especially at sections 9-12 on how to best pose your question. In particular, please read FAQ #12 and help those whose help you seek by posting example data using the dataex command. If you are running Stata 15.1 or later, it is already installed. For earlier versions of Stata, install dataex by typing ssc install dataex. Type help dataex to read the simple instructions for using it. Using dataex will enable those who want to help you to quickly and easily create a 100% faithful replica of your situation to test their ideas and code on.

    The more you help others understand your problem, the more likely others are to be able to help you solve your problem.

    Comment


    • #3
      Thank you William. Will take your advice for next time

      Comment

      Working...
      X