Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Looping over mean

    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


    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!

  • #2
    To extract that value after an estimation command like mean use
    Code:
    ereturn list
    to see the output in terms of macros, scalars and matrices.
    In this case what you want is:
    Code:
    loc mean=e(b)[1,1]
    di `mean'
    putexcel C`row' = `mean'

    Comment


    • #3
      Hi Alejoforero - it worked perfectly. Thanks!

      Comment

      Working...
      X