I have a panel dataset with the following key variables: race, wealth, year. Race is a string variable with the following categories: black, Hispanic, white.
I wish to generate mean wealth for each race by year using the foreach/forval commands. I tried running the following code:
foreach i in black Hispanic white {
2. egen meanwealth_`i' = mean(wealth) if race==`i', by(year)
3. }
Stata returns the following error message: black not found r(111);
I then encoded the race variable, calling the new variable race1 and ran the following code:
forval i = 1/3 {
2. egen meanwealth_`i' = mean(wealth) if race1==`i', by(year)
3. }
The code worked perfectly but instead of having variables like meanwealth_black I now have variables like meanwealth_1.
How can I have my variables be named after their categories instead of numbers when using the foreach command?
Thanks in advance for any and all help.
Related Posts with Using the foreach/forval commands for different categories of a categorical variable
filling missing data per id from cells below.Dear Stata Community, I am working with long panel data. I have multiple observations per id. In m…
Urgent estimation problemHello, I have 2 survey waves nad i did a probit, I saw a lot of papers include a variable loe ''wave…
Oaxaca decomposition (nledcompose): how to deal with categorical Y'sDear all, I am new to the Oaxaca-Blinder decomposition, and I'ld like to know your opinion about ho…
Collinearity IssuesDear All, I apologise in advance if this is a really basic question, but I am very new to stata. I…
Label variable over multiple linesI want to label multiple variables in my dataset in one command, like below: lab var /// id "ID" //…
Subscribe to:
Post Comments (Atom)
0 Response to Using the foreach/forval commands for different categories of a categorical variable
Post a Comment