Hi everyone! I am trying to complete a database in form of a "tree", adding as values the last available observation when a new branch exists. This is, for level 1 I need all the observations ( I already got this), but for the subsequent levels I just need to complete those obvservations for which the next level is not missing. Eg: I should have all observations marked with X:
I encoded all variables. Since I have 8 levels, I got the correct result by using 6 loops like this (one for each level and running them from the 7th to 1)
foreach var of varlist *7{
replace `var'=`var'[_n-1] if id8!=.
}
and another for the first level:
foreach var of varlist *1{
replace `var'=`var'[_n-1] if `var'==.
}
What I am trying now is to simplify the code by unifying the 6 loops only into 1, but i can´t find out how. I have tried something like this but the result is not correct.
foreach var of varlist id2-cod7{
local numvar = substr("`var'", -1,.)
rename `var' `var'_`numvar'
replace `var'_`numvar' = `var'_`numvar'[_n-1] if `var'_`numvar'+1!=.
}
I would really appreciate if anyone could give a hint of how to proceed!
| id1 | name1 | cod1 | id2 | name2 | cod2 | id3 | name3 | cod3 | id4 | name4 | cod4 |
| X1 | Hotel1 | 879 | |||||||||
| X | X | X | X2 | Hotel2 | 456 | ||||||
| X | X | X | X | X | X | X31 | Hotel31 | 447 | |||
| X | X | X | X | X | X | x32 | Hotel32 | 775 | |||
| X | X | X | X | X | X | X33 | Hotel33 | 656 | |||
| X | X | X | X | X | X | X | X | X | X4 | Hotel4 | 894 |
foreach var of varlist *7{
replace `var'=`var'[_n-1] if id8!=.
}
and another for the first level:
foreach var of varlist *1{
replace `var'=`var'[_n-1] if `var'==.
}
What I am trying now is to simplify the code by unifying the 6 loops only into 1, but i can´t find out how. I have tried something like this but the result is not correct.
foreach var of varlist id2-cod7{
local numvar = substr("`var'", -1,.)
rename `var' `var'_`numvar'
replace `var'_`numvar' = `var'_`numvar'[_n-1] if `var'_`numvar'+1!=.
}
I would really appreciate if anyone could give a hint of how to proceed!

Comment