Announcement

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

  • How to create a string variable with the string value of the variable name?

    I am trying to use merge on two data sets, one which has a value for PID for approximately 1700 observations. The other data set has variables named PID which have values for 366 days of a year, but to merge them I need to create a variable for those with the name PID so I have something to merge to.

    Trick is, how to create a new variable with the string name to match what is in the other dataset?

    Or there may be easier ways to do this. Everything I see in merge requires I have a variable with which to merge or joinby.

    Thank you.

    dp

    Click image for larger version

Name:	Describe.JPG
Views:	1
Size:	155.4 KB
ID:	1478187
    Click image for larger version

Name:	Capture2.JPG
Views:	1
Size:	61.0 KB
ID:	1478188

  • #2
    The first data set is in wide layout, which is often difficult to work with in Stata. You need to make it long, and then it will merge easily with the other:

    Code:
    use control_2016_nonpool_daily_bysite, clear
    ds day, not
    rename (`r(varlist)') mean_=
    reshape long mean_, i(day) j(pid) string
    After that you can easily -merge- on pid with the second dataset. I cannot tell from what you show whether this will be a 1:1 or a 1:m merge, but you can figure that out.

    In the future, when showing data examples, please use the -dataex- command to do so. If you are running version 15.1 or a fully updated version 14.2, -dataex- is already part of your official Stata installation. If not, run -ssc install dataex- to get it. Either way, run -help dataex- to read the simple instructions for using it. -dataex- will save you time; it is easier and quicker than typing out tables. It includes complete information about aspects of the data that are often critical to answering your question but cannot be seen from tabular displays or screenshots. It also makes it possible for those who want to help you to create a faithful representation of your example to try out their code, which in turn makes it more likely that their answer will actually work in your data.


    When asking for help with code, always show example data. When showing example data, always use -dataex-.

    Comment

    Working...
    X