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
Replication code for Stata 14 and Stata16 producing different resultsI ran into a problem where a data replicator could not replicate an item response variable using the…
margins with multiple imputed dataHello, Is there a way to use the margins command with multiple-imputed data? I'm working with the f…
matching counties based on first two digits for finding similar stateHello, I have a data which shows distance between all counties from another county. This includes a…
Data being destroyed while savingI'm having a very weird problem with data being destroyed while writing/reading into Stata-MP on a s…
How to combine 2 rows of data into 1 row_Dear stata user, I'm trying to combine 2 or more rows of information into 1 row, because they are a…
Subscribe to:
Post Comments (Atom)
0 Response to Using the foreach/forval commands for different categories of a categorical variable
Post a Comment