I have a panel data set with country, years, and the following three (relevant) variables:
C (float)
code (string)
varcode (string)
code has string values such as "a", "b", "c", etc.
varcode has string values such as "i_it_a", "i_it_b", "i_it_c", etc.
I am trying to create a new variable, i_gfcf_<code>, for each value of code, which sums over the values of C for certain values of varcode. See the loop below:
local title code
foreach x of varlist code{
egen i_gfcf_`x' = sum(C) if (varcode == "i_it_`x'") | (varcode == "i_ct_`x'") | (varcode == "i_soft_`x'") | (varcode == "i_traeq_`x'") | (varcode == "i_omach_`x'") | ///
(varcode == "i_ocon_`x'") | (varcode == "i_rstruc_`x'") | (varcode == "i_other_`x'")
}
PROBLEM: After running this loop, I obtain only one new variable, i_gfcf_code. But code is a variable name, not a value of the variable, i.e. I would expect to have only i_gfcf_a, i_gfcf_b, i_gfcf_c, etc. What's more, i_gfcf_code is incorrectly missing for all observations.
QUESTION: How can I structure the above loop such that each value of the variable code is used to
(i) generate a new variable named after that particular value of code, e.g. i_gfcf_a, i_gfcf_b, etc. and
(ii) adjust the if statement for each value of code, e.g. if (varcode == "i_it_a") | (varcode == "i_ct_a"), etc. or if (varcode == "i_it_b") | (varcode == "i_ct_b"), etc. ?
Thank you so much.
Related Posts with Foreach and string variables
-Coefplot- Rotating GraphHi, I installed -coefplot-, created by Nick Cox and I am having some trouble manipulating the graph.…
Multencode: New Variables QuestionHello, I've been trying to synchronize value labels from multiple surveys. I first decoded all nume…
estat sarganHi experts, I tried to run estat sargan and estat abond but each time an error is generated "invalid…
HLM - Level 1 Sample Size within sub-groupsHello, I am planning to fit an HLM model predicting the odds of HIV risk behavior among people who …
Calculation across cells using an identifier variableHello Community, I hope someone can help me out with my Stata problem. Basically, I would like to …
Subscribe to:
Post Comments (Atom)
0 Response to Foreach and string variables
Post a Comment