Hi Stata Community,
I hope you are all doing well! I got a (hopefully) quick question relating to how to loop over a mean. In particular, I got a variable that is called change1m_ that I would like to take the mean of if the dummy variable called flag equals 1. Without a loop, this should be
Now my question is:
(a) how do I loop over this for different year and month combinations and
(b) how do I save the respective value so I can import it into Excel? Please see my (unsuccessful) attempt below:
The data in the data editor basically look like this
Thank you so much!
I hope you are all doing well! I got a (hopefully) quick question relating to how to loop over a mean. In particular, I got a variable that is called change1m_ that I would like to take the mean of if the dummy variable called flag equals 1. Without a loop, this should be
HTML Code:
mean change1m_ if flag ==1
Now my question is:
(a) how do I loop over this for different year and month combinations and
(b) how do I save the respective value so I can import it into Excel? Please see my (unsuccessful) attempt below:
HTML Code:
putexcel set Trimmed_PCE.xlsx, sheet(data) replace putexcel A1 = "Year" putexcel B1 = "Month" putexcel C1 = "Trimmed mean" local row = 2 forvalues y = 2021(1)2021 { forvalues m = 1(1)12{ preserve keep if year==`y' & month==`m' sort change1m_ gen cum`y'`m' = sum(weight) generate flag`y'`m' = 1 replace flag`y'`m' = 0 if cum`y'`m'>=69 | cum`y'`m'<=25 mean change1m_ if flag ==1 putexcel A`row' = `y' putexcel B`row' = `m' putexcel C`row' = local ++row restore } }
The data in the data editor basically look like this
category | change1m_ | year | month | day | weight_ | modate | cum | flag |
CPIVGRAPIndex | -31.038 | 2021 | 9 | 30 | 0.186 | 2021m9 | 0.186 | 0 |
CPIVWOAPIndex | -26.7469 | 2021 | 9 | 30 | 0.884 | 2021m9 | 1.07 | 0 |
CPIVCFVEIndex | -1.5016 | 2021 | 9 | 30 | 0.148 | 2021m9 | 18.76933 | 1 |
CPIVABHOIndex | -0.65833 | 2021 | 9 | 30 | 0.562 | 2021m9 | 19.33133 | 1 |
CPIVCHICIndex | -0.32432 | 2021 | 9 | 30 | 0.279 | 2021m9 | 19.61033 | 1 |
CPIVEGECIndex | -0.28941 | 2021 | 9 | 30 | 0.351 | 2021m9 | 19.96133 | 1 |
CPIVFUOIIndex | 58.14851 | 2021 | 9 | 30 | 0.096 | 2021m9 | 98.8795 | 0 |
CPIVBEVEIndex | 74.84962 | 2021 | 9 | 30 | 0.515 | 2021m9 | 99.3945 | 0 |
Thank you so much!
Comment