Announcement

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

  • Changing a set of variables in a dataset

    Hello Everyone,

    I have several datasets coming from different studies. My goal is two merge all those datasets into one single dataset.
    Some variables in different datasets have the same variable name, so in order to merge the datasets, I need to change the variable names.
    I want to change the variable names based on the study they originate. For example, for all variables in the first dataset, I want them to start with 1_variable_name. And the variables from the second dataset, I want them to begin with 2_variable_name. Since I have a lot of variables in the dataset, I was wondering if it is possible to change the variable names with a simple command rather than changing their names one by one. I would highly appreciate your advice on this.

  • #2
    Nick, variable names in Stata cannot begin with a number. But a simple command that would change all the variable names in a dataset might be:

    Code:
    rename * d1_*
    Just keep in mind that if you are using merge to combine these datasets, you will probably need a key variable that is named the same across the various datasets. You can then rename just that one back to its original name by doing something like

    Code:
    rename d1_keyvar keyvar
    Last edited by Hemanshu Kumar; 29 Aug 2022, 05:30.

    Comment


    • #3
      On the whole this sounds like a problem for append, not merge.

      But what you ask is possible: see

      Code:
      help rename groups

      Comment


      • #4
        Originally posted by Hemanshu Kumar View Post
        Nick, variable names in Stata cannot begin with a number. But a simple command that would change all the variable names in a dataset might be:

        Code:
        rename * d1_*
        Just keep in mind that if you are using merge to combine these datasets, you will probably need a key variable that is named the same across the various datasets. You can then rename just that one back to its original name by doing something like

        Code:
        rename d1_keyvar keyvar
        Dear Hemanshu,

        Thank you very much for the advice and the clarification!

        Comment


        • #5
          Originally posted by Nick Cox View Post
          On the whole this sounds like a problem for append, not merge.

          But what you ask is possible: see

          Code:
          help rename groups
          I will dig more into append command. Thank you for your advice!

          Comment

          Working...
          X