[英]Stata sum/average over a range
使用以下數據集。
id date date1a date1b date2a date2b variable
1 1/1/2000 2/6/2009 8/9/2009 7/14/2010 9/2/2010 7
1 1/2/2000 2/6/2009 8/9/2009 7/14/2010 9/2/2010 2
1 1/2/2000 2/6/2009 8/9/2009 7/14/2010 9/2/2010 11
...
1 1/1/2013 2/6/2009 8/9/2009 7/14/2010 9/2/2010 9
1 1/8/2013 2/6/2009 8/9/2009 7/14/2010 9/2/2010 8
2 2/2/2010 6/1/2010 7/9/2011 4/6/2012 5/1/2012 4
2 2/2/2010 6/1/2010 7/9/2011 4/6/2012 5/1/2012 3
2 2/2/2010 6/1/2010 7/9/2011 4/6/2012 5/1/2012 1
...
2 5/1/2012 6/1/2010 7/9/2011 4/6/2012 5/1/2012 1
2 5/1/2012 6/1/2010 7/9/2011 4/6/2012 5/1/2012 1
我想創建變量sum1
和average1
和sum2
和average2
,其履行這些操作variable
的日期范圍之間date1a
到date1b
(用於sum1
和average1
)和date2a
到date2b
(為sum2
和average2
)。
現在,我的方法費力,容易出錯,並且沒有捕捉到我當天有重復條目的事實。 另外,如果沒有與date1b
或date2b
匹配的date
,那么我需要手動進行編輯。
sort date
gen date1range = date1b - date1a
local j = date1range
forval i = 1/`j' {
by id: gen variableforcalc`i' = variable[_n-`i']
}
egen sum1 = rowtotal(variableforcalc*)
egen average1 = rowmean(variableforcalc*)
gen dateflag = 0
replace dateflag = 1 if date == date1b
我看到我停止閱讀您的代碼
local j = date1range
這將被解釋為
local j = date1range[1]
因此不能作為一般解決方案的基礎。
您可以初始化
gen sum1 = .
gen average1 = .
並根據相同的id
, date1a
和date1b
egen group = group(id date1a date1b)
su group, meanonly
然后遍歷group
的不同值
quietly forval j = 1/`r(max)' {
* start and end dates and id should be identical in each group; this is just look-up
su date1a if group == `j', meanonly
local d1 = r(min)
su date1b if group == `j', meanonly
local d2 = r(min)
su id if group == `j', meanonly
local this = r(min)
su variable if id == `this' & inrange(date, `d1', `d2'), meanonly
replace sum1 = r(sum) if group == `j'
replace mean1 = r(mean) if group == `j'
}
另一個總和和均值應接受相同的處理。
http://www.stata-journal.com/sjpdf.html?articlenum=pr0033中討論了結構大致相似的一些問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.