Hi -
I'm interested in looking at an average quantity (of AvgOfWeight) over the past month (Date is the time variable) -- not by month. This value would thus address the fact that the most recent 30 days on Apr 3 is a more relevant 'month' than the average across April.
To do this, I want to average over the most recent 30 days. The following code works to generate the solution, but I've seen previous recommendations that using a loop over observations is not a great practice. Could anyone suggest another, and ideally more efficient, way to generate the same result?
Many thanks for your help!
Katie
gen lastMonth = .
local N = _N
forvalues i = 1/`N' {
quietly summarize AvgOfWeight if (Date <= Date[`i'] & Date >= Date[`i']-30)
replace lastMonth = r(mean) in `i'
}
I'm interested in looking at an average quantity (of AvgOfWeight) over the past month (Date is the time variable) -- not by month. This value would thus address the fact that the most recent 30 days on Apr 3 is a more relevant 'month' than the average across April.
To do this, I want to average over the most recent 30 days. The following code works to generate the solution, but I've seen previous recommendations that using a loop over observations is not a great practice. Could anyone suggest another, and ideally more efficient, way to generate the same result?
Many thanks for your help!
Katie
gen lastMonth = .
local N = _N
forvalues i = 1/`N' {
quietly summarize AvgOfWeight if (Date <= Date[`i'] & Date >= Date[`i']-30)
replace lastMonth = r(mean) in `i'
}
Comment