0
votes

I'm importing a very complex .xls file that often combines multiple cells together in the variable names. After importing it into Stata, only the first cell has a variable name, and the other 3 are blank. Is it possible to write a loop to rename all the variables (which come in sets of 4)?

For instance, the variables go: Russia, B, C, D but I would like them to be named Russia_A, Russia_B, Russia_C, Russia_D. Is there a way to do this with a loop or command within Stata?

1
I didn't downvote but I can easily guess that the absence of a reproducible example and of any attempt at code led to the downvote. See stackoverflow.com/help/mcveNick Cox

1 Answers

3
votes

It's impossible to have blank variable names in Stata, as your own example attests. On the information given your variable names come in fours, so that you could loop. One basic technique is just to cycle over 1, 2, 3, 4 and act accordingly. This example works. If it's not what you want, a minimal reproducible example is essential showing why this is different from what you want.

clear 

input Russia B C D Germany E F G France H I J
42 42 42 42 42 42 42 42 42 42 42 42
end

tokenize "A B C D" 

local i = 0 
foreach v of var * { 
    local ++i 
    if `i' == 1 local stub "`v'" 
    rename `v' `stub'_``i'' 
    if `i' == 4 local i = 0 
} 

ds


Russia_A   Russia_C   Germany_A  Germany_C  France_A   France_C
Russia_B   Russia_D   Germany_B  Germany_D  France_B   France_D

tokenize is possibly the least familiar command here, so see its help if needed.

All that said, it's unlikely that this is a useful data structure. See help reshape.

Here's another way to do it. We set up a counter running over all the variables. This perhaps is more of a finger exercise in macro manipulation.

clear 

input Russia B C D Germany E F G France H I J
42 42 42 42 42 42 42 42 42 42 42 42
end

tokenize "A B C D" 
forval j = 1/4 { 
    local sub`j' "``j''" 
} 

unab all : * 
tokenize "`all'" 
local J : word count `all' 

forval j = 1/`J' { 
    local k = mod(`j', 4) 
    if `k' == 0 local k = 4 

    if `k' == 1 local stub "``j''" 
    rename ``j'' `stub'`sub`k'' 
} 

ds