I have a dataset in wide format that has quarterly counts of an event from Q1
1996
to Q4
2016
.
The variable names for each quarter are as follows:
yyyy0101_yyyy0401
yyyy0401_yyyy0701
yyyy0701_yyyy1001
yyyy1001_yyyy0101
I have a macro that converts them like this:
local i = 1996
forvalues x = 1996/2016 {
local i = `i'+1
gen count`x' = event_`x'0101_`x'0401 + event_`x'0401_`x'0701 +
event_`x'0701_`x'1001 + event_`x'1001_`i'0101
}
Then I collapse my data into a single variable count
in long format by year:
reshape long count, i(xvars) j(year)
Now I would like to do the same thing, but quarterly.
What is the macro to perform the exact same process, but capturing the sum of counts by year-quarter? What if I wanted to do it for half years?
答案 0 :(得分:0)
在试图理解这一点时,我首先(迂腐地或其他方面)注意到你的代码不是Stata意义上的宏:SAS用户???)和第二个(更具建设性)你的代码可以被压缩到
forvalues x = 1996/2016 {
gen count`x' = event_`x'0101_`x'0401 + event_`x'0401_`x'0701 + event_`x'0701_`x'1001 + event_`x'1001_`x'0101
}
鉴于本地宏i
和x
运行相同的值。 (这些都是Stata意义上的宏。)但我不会从那里开始。
正如你所说,数据是宽格式的(我更喜欢术语布局减少重载),所以主要工作不是写循环,而是reshape
长。这个例子体现了一些猜测并展示了一些技巧。如果没有要使用的数据示例,我首先创建一个沙箱:
clear
set obs 21
local y = 1
foreach v in yyyy0101_yyyy0401 yyyy0401_yyyy0701 yyyy0701_yyyy1001 yyyy1001_yyyy0101 {
gen `v' = `++y'
}
gen year = 1995 + _n
rename (yyyy*) (count#), addnumber
reshape long count, i(year) j(quarter)
gen qdate = yq(y, q)
egen ycount = total(count), by(year)
egen qcount = total(count), by(quarter)
gen half = cond(inlist(quarter, 1, 2), 1, 2)
egen hcount = total(count), by(year half)
list if year < 1998, sepby(year)
+------------------------------------------------------------------+
| year quarter count qdate ycount qcount half hcount |
|------------------------------------------------------------------|
1. | 1996 1 2 144 14 42 1 5 |
2. | 1996 2 3 145 14 63 1 5 |
3. | 1996 3 4 146 14 84 2 9 |
4. | 1996 4 5 147 14 105 2 9 |
|------------------------------------------------------------------|
5. | 1997 1 2 148 14 42 1 5 |
6. | 1997 2 3 149 14 63 1 5 |
7. | 1997 3 4 150 14 84 2 9 |
8. | 1997 4 5 151 14 105 2 9 |
+------------------------------------------------------------------+
与您使用reshape long
时的情况有何不同?主要是要强调在不同时间尺度上你想要的任何总数都可以在适当的位置生成。您不需要重复collapse
个或同一数据集的不同版本。如何制表,列表或以其他方式处理重复将是不同的问题。