Announcement

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

  • Renaming part of a variable using loops

    I am trying to rename a large number of variables that correspond to various survey waves. We have to follow up surveys where each variable from the first follow up end begins with "a_" and each variable name from the second follow-up begins with "b_".

    I would like to rename each of these variables using a loop but want to switch the "a_" and "b_" from the beginning of the each of the variable names to the end so each variable shows up as "var_a" and "var_b"

    I have the following code to add the "_a" and "_b" to the end of the variables but am unsure how to rename the variables to drop "a_" and "b_" from the front part of the variable names.

    My current code is:
    global a_varlist vars
    foreach var of varlist $a_varlist {
    rename `var' `var'_a
    }

    global b_varlist vars
    foreach var of varlist $b_varlist {
    rename `var' `var'_b
    }
    Last edited by Wyatt Pracht; 01 May 2023, 22:00.

  • #2
    It's unnecessary to use a loop, but what is the real variable names in your dataset? Just a_, b_, ......? Suppose your variables are named a_here, b_there, then
    Code:
    rename (a_*) (*_a)
    rename (b_*) (*_b)

    Comment

    Working...
    X