I'm trying to produce summary statistics of a variable efficiently as it will have to be done numerous times.
I've created an categorical age variable and I would like to write the count and sum for those in grades 10 and above by the age categories to excel using a loop.
I think it involves the use of 3 loops? The first two loops work correctly in the sense that for the two age categories, the count and sum have been written to matrices for grades 10 - 18. The last loop isn't working whereby I would like to write the aforementioned to excel. The problem is that the putexcel command is writing the sum and count for each grade into every excel column specified and subsequently being overwritten by the next grade with the end result being the sum and count for grade 18 written into every column on excel. I'm trying to get the loop to write it for each grade then move onto the next one with the end result being 9 columns in excel with the count and sum of the wage for each age category for each grade of high school. I've tried numerous variations of the code but cannot get it to work.
If this cannot be achieved, I would be interested to hear any thoughts/suggestions on next best ideas to write summary statistics of this nature to excel quickly. For example if I wanted to write the sum and count of profits of firms by industry for each year to excel how would one achieve this efficiently.
Any thoughts/suggestions would be very much appreciated.
Code:
clear all sysuse nlsw88.dta * **generate categorical age variable sum age generate byte agecat=. replace agecat=1 if age>=30 & age<40 & age!=. replace agecat=2 if age>=40 & age<=50 & age!=. label variable agecat "Age category" label define agecatl 1 "30-40 Years Old" label define agecatl 2 "40-50 Years Old", add label values agecat agecatl tab agecat tab grade tabstat wage if grade>=10, by(agecat) s(n sum) format(%20.0fc) save return list // **Grades 10 and above local letter C E G I K M I O Q S putexcel set "Wage Stats", sheet("Age") modify foreach i in 0 1 2 3 4 5 6 7 8 { display 1`i' tabstat wage if grade==1`i', by(agecat) s(n sum) format(%20.0fc) save forvalue j =1/2 { matrix m`j'=(r(Stat`j')') } matrix sector_`j' = (m1\m2) matrix list sector_`j' foreach m of local letter { putexcel `m'20 = matrix(sector_`j') } }
0 Response to Combining multiple loops to write summary statistics to excel efficiently.
Post a Comment