If I have a variable in Stata that has a number, can I use that value embedded in a formula?
For example, I variable days (days
) and for each individual I want to use that number in a second formula:
ID Days var_x_1 var_x_2 var_x_3 var_x_4 var_x_5 var_x_6
A 2 7 8 9 10 2 1
B 1 1 7 1 11 12 11
C 6 7 9 2 12 6 12
D 2 2 4 3 17 7 18
gen new_var = var_x_DAYS
Variable new_var
would take the value in Days
and pull the corresponding from the var_x
list:
ID new_var
A 8
B 1
C 12
D 4
I have tried:
local DaysUse = Days
g new_var = var_x_`DaysUse'
However, this did not work.
That last statement could be perfectly legal; it just doesn't do what you want. Consider
local DaysUse = Days
g new_var = var_x_`DaysUse'
A local macro is just some text. More crucially, it is a text constant or scalar, not a variable or vector of text elements. Here Stata will understand you as wanting
local DaysUse = Days[1]
so that your local
will contain the string 2
, at least for your example, so that
g new_var = var_x_2
will be the net result after macro substitution. If you went
local DaysUse = "Days"
you would get
g new_var = var_x_Days
which is no use here.
There is more positive technique for your problem.
gen new_var = .
quietly forval j = 1/6 {
replace new_var = var_x_`j' if Days == `j'
}
Stata has something a little like what you want. Consider
sysuse auto, clear
set seed 2803
gen index = ceil(runiform() * 74)
gen bsample_mpg_1 = mpg[index]
gen bsample_mpg_2 = mpg[ceil(runiform() * 74]
as two ways of getting bootstrap samples in place. But that doesn't extend to what you asked for.