I have decided to put some code in my blog because my friends do ask me how to run things. Yes, there are many good Stata and other program material online but I hope mine  can be helpful as well.

Q: How to run regression by country and save the R squares?

If you do financial/accounting research, you often have to run regressions by certain groups and save the regression results. The code below does the job.

**Create a numeric ID using egen command.

egen country_id=group(country_var)

**Create empty variable to store the R square

gen r2=.

**Run a forvalues loops and save the R square for each country regression

forvalues i=1(1)[last value of country_id]{

reg y x if country_id==`i’

replace r2=e(r2_a)



Real example using Stata’s Auto data


sysuse auto.dta

egen country_id=group(foreign)

***Creates two ids 1,2 (domestic and foreign)

gen r2=.

forvalues i=1(1)2{
reg price mpg if country_id==`i’
replace r2=e(r2_a)  if country_id==`i’


Please like the post if it was helpful and if it helped you save time! If you have more questions, please do comment and we will learn together 😀

Happy coding ^^