【发布时间】:2018-01-21 09:40:08
【问题描述】:
我需要创建一个变量,告诉我自第一次观察特定组以来的年数,conflictID。我提供了一个示例数据集来说明我的问题。
conflictID <- c(205,205,205,209,209,221,221,221,221)
year <- c("1993", "1995", "1996", "1991", "1993", "2001", "2002", "2003", "2005")
df <- data.frame(conflictID, year)
这个数据框的输出是:
conflictID year
1 205 1993
2 205 1995
3 205 1996
4 209 1991
5 209 1993
6 221 2001
7 221 2002
8 221 2003
9 221 2005
我想要这样的东西:
conflictID year duration
1 205 1993 0
2 205 1995 2
3 205 1996 3
4 209 1991 0
5 209 1993 2
6 221 2001 0
7 221 2002 1
8 221 2003 2
9 221 2005 4
其中 duration 变量对于每个 conflictid 的第一次观察为 0。基本上,如果有意义的话,我需要一种为每个 conflictID 的第一年设置基准日期的方法?
【问题讨论】:
标签: r date dataframe datediff panel-data