我需要创建一个变量来告诉我自第一次观察特定组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)
Run Code Online (Sandbox Code Playgroud)
该数据帧的输出是:
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
Run Code Online (Sandbox Code Playgroud)
我想要看起来像这样的东西:
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 …Run Code Online (Sandbox Code Playgroud)