这个问题是twoway line
带有by()
选项的上下文,但我认为更大的问题是如何在没有先验知道每个事件窗口的情况下识别第二个(以及所有后续的)事件窗口
下面我在20世纪90年代和21世纪初为五个国家生成一些数据。在所有国家,事件发生在1995年,在加拿大只有事件在2005年重复。我想在五年内以每个国家的每个事件为中心绘制outcome
。如果我使用twoway line
和by()
执行此操作,则加拿大会在同一个绘图窗口中绘制两次。
clear
set obs 100
generate year = 1990 + mod(_n, 20)
generate country = "United Kingdom" in 1/20
replace country = "United States" in 21/40
replace country = "Canada" in 41/60
replace country = "Australia" in 61/80
replace country = "New Zealand" in 81/100
generate event = (year == 1995) ///
| ((year == 2005) & (country == "Canada"))
generate time_to_event = 0 if (event == 1)
generate outcome = runiform()
encode country, generate(countryn)
xtset countryn year
forvalue i = 1/2 {
replace time_to_event = `i' if (l`i'.event == 1)
replace time_to_event = -`i' if (f`i'.event == 1)
}
twoway line outcome time_to_event, ///
by(country) name(orig, replace)
手动解决方案会添加occurrence
变量,该变量按国家/地区对每个事件的出现次数进行编号,然后将occurrence
添加到by()
选项。
generate occurrence = 1 if !missing(time_to_event)
replace occurrence = 2 if ///
(inrange(year, 2005 - 2, 2005 + 2) & (country == "Canada"))
twoway line outcome time_to_event, ///
by(country occurrence) name(attempt, replace)
这在播放数据中效果很好,但在我的真实数据中,还有更多国家和更多活动。我可以手动编写这个occurrence
变量,但这很乏味(现在我真的好奇,如果有一个工具或逻辑可行:)。
是否有自动识别窗口的逻辑?或者至少与twoway line
一起使用?谢谢!
答案 0 :(得分:2)
您已在窗口中生成了变量time_to_event
,即-2 .. 2,否则将丢失。您可以使用SSC中的tsspell
,由
ssc inst tsspell
标记此类窗口。 Windows是由time_to_event
上的所有非遗漏的法术或观察行定义的:
tsspell, cond(time_to_event < .)
tsspell
需要先前的tsset
,并在其帮助中生成三个变量。然后,您可以使用其中一个变量_seq
重新编号窗口(法术中的序列号,编号为1)
gen _spell2 = (_seq > 0) * sum(_seq == 1)
然后使用country
和来自_spell
的每个法术的法术标识符明确标记法术,tsspell
生成另一个变量:
egen gspell = group(country _spell) if _spell2, label
我的代码假设窗口是不相交的,不能重叠,但这似乎也是你的假设之一。处理法术的一些技巧由http://www.stata-journal.com/sjpdf.html?articlenum=dm0029给出。该文章未提及tsspell
,其实质上是其原则的实现。我开始解释原理,但在我解释程序之前,文章已经足够长了。由于tsspell
的帮助非常详细,我怀疑是否需要续集文件,或者至少它是否会被写入。
(稍后)此代码还假定窗口不触及。解决这个问题表明一种更直接的方法,根本不涉及tsspell
:
bysort country (year) : gen w_id = (time_to_event < .) * sum(time_to_event == -2)
egen w_label = group(country w_id) if w_id, label