My dataset contains multiple variables called avar_1
to bvar_10
referring to the history of an individual. For some reasons, the history is not always complete and there are some "gaps" (e.g. avar_1
and avar_4
are non-missing, but avar_2
and avar_3
are missing). For each individual, I want to store the first non-missing value in a new variable called var1
the second non-missing in var2
etc, so that I have a history without missing values.
I've tried the following code
local x=1
foreach wave in a b {
forval i=1/10 {
capture drop var`x'
generate var`x'=.
capture replace var`x'=`wave'var`i' if !mi(`wave'`var'`i')
if (!mi(var`x')) {
local x=1+`x'
}
}
}
var1
is generated properly but var2
only contains missings and following variables are not generated. However, I set trace on
and saw that the var2
is actually replaced for all variables from avar_1
to bvar_10
.
My guess is that the local x
is not correctly updated as its value change for the whole dataset but should be different for each observation.
Is that the problem and if so, how can I avoid it?