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.
0 Response to Using the foreach/forval commands for different categories of a categorical variable
Post a Comment