multiple errors in renaming a group of variables and concatenating a suffix

StackOverflow https://stackoverflow.com/questions/22109595

  •  18-10-2022
  •  | 
  •  

Pregunta

I'm spending a lot of time doing something that should be pretty simple. I'm trying to change a group of variables to have the same name but with a different letter on the end. I'm not understanding how arrays work or something: probably multiple things are wrong with my syntax, as I'm very unfamiliar with Stata. I've been Googling for hours and can't figure this out and need to get away from the computer for a while.

local letters `" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" "'
local i 1
local swap " "

foreach var of varlist q5_a-q5_o {
    local letter : word `i' of `letters' //select the 1st value in the array which is 'a'
    replace `swap' = "aspects" + "_" + `letter' //change swap to read 'aspects_a' 
    rename `var' `swap' //rename 'q5_a' to 'aspects_a'
    local `i' = `i' + 1 //add one to 'i' so that the next loop will change 'q5_b' to 'aspects_b'
}
¿Fue útil?

Solución

As @Dimitriy V. Masterov points out, rename (in Stata 12 up) is capable of multiple renamings.

Indeed,

renpfix q5 aspect

would seem to be what you wanted.

The rest of this answer focuses on what was wrong with your approach. In your case, the first time you call up

replace `swap' = 

local macro swap is just spaces, so Stata sees

replace = 

which is illegal. But the whole idea of using replace is wrong here. It is not how to change local macros at all. In short, you are misreading replace as a way to manipulate strings. It is a way to change the contents of variables.

local letters `c(alpha)' 
local i = 1

foreach var of varlist q5_a-q5_o {
    local letter : word `i' of `letters' 
    rename `var' aspects_`letter' 
    local i = `i' + 1 
}

should work. Here we are exploiting the fact that the lower case letters "a" to "z" are already in c(alpha): see towards the end of the output of creturn list for other useful bits and pieces. This could be made shorter:

local letters `c(alpha)' 
local i = 1

foreach var of varlist q5_a-q5_o {
    local letter : word `i++' of `letters' 
    rename `var' aspects_`letter' 
}

and shorter still:

local i = 1

foreach var of varlist q5_a-q5_o {
    local letter : word `i++' of `c(alpha)' 
    rename `var' aspects_`letter' 
}

and shorter still

foreach letter in `c(alpha)' { 
     rename q5_`letter' aspect_`letter' 
} 

although as implied earlier this is what renpfix does for you any way.

Otros consejos

Try group rename: rename q5* aspects*. If that's not what you want, give an example of some current variable names and their desired new names.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top