Announcement

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

  • Rename variable list with a different variable's values

    I apologize in advance for this question. I'm currently using Stata 15.1.

    Let's say you have the following dataset:

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str7 respondent_id byte(var1 var2 var3)
    "_0001" 0 0 0
    "_0005" 0 0 1
    "_0007" 0 0 0
    end
    I would like to come up with code that will do the following renames:
    Code:
    rename var1 var_0001
    rename var2 var_0005
    rename var3 var_0007
    Obviously, if I only had those three variables I could just do it by hand. But I have about 15 datasets like this, ranging from about 50 to 250 "var" variables. While the "var" variables always go in sequential order, the respondent_id variable has gaps that don't follow any known rule.

    I suspect there is some way to map the "var" variables onto the values of "respondent_id", either using a loop with rename or with renvars, but I have no idea where to begin. Does anyone have resources or ideas of code that would do this?

  • #2
    Never mind! I figured it out:

    Code:
    forval j = 1/3  {
         rename var`j' `=strtoname(respondent_id[`j'])'
    }
    Sorry to clog things up.

    Comment


    • #3
      Yes, that code will do what you asked, but why do you want that? It makes no sense to me. The values of the variables var1, var2 and var3 are attributes of all the different respondents, not just of one. It would make equally good (actually, equally poor) sense to do the renaming in some other arbitrary order of the respondents.

      The only way I can see for what you have done to be sensible is if what you have is not really a data set but some kind of matrix masquerading as a data set where, for example, the value in the second row and final column represents some joint attribute of respondents _0005 and _0007. But if that's actually what you have, then it would probably better to either -reshape- the whole thing into long layout, which will enable you to work with the data more readily in Stata, or actually make a matrix out of it, if you plan to do matrix algebra on these numbers.

      Comment


      • #4
        Yes, that's it--it's a matrix where row and column are equivalent, but for some reason the variables (the columns of the matrix) are labeled differently than the observations (the rows of the matrix). I don't know why it is that way. But it is.

        Comment

        Working...
        X