创建自基本观察以来的年数计数变量

Lee*_*ria 0 datediff r date dataframe panel-data

我需要创建一个变量来告诉我自第一次观察特定组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     2002       1
8        221     2003       2
9        221     2005       4
Run Code Online (Sandbox Code Playgroud)

其中每个冲突的第一个观察的持续时间变量为 0 。基本上,我需要的是一种为每个冲突ID的第一年设置基准日期的方法,如果这有意义的话?

www*_*www 5

我们可以使用dplyr图书馆。df2是最终的输出。

library(dplyr)

df2 <- df %>%
  mutate(year = as.numeric(as.character(year))) %>%
  group_by(conflictID) %>%
  mutate(duration = year - min(year))

df2
# A tibble: 9 x 3
# Groups:   conflictID [3]
  conflictID  year duration
       <dbl> <dbl>    <dbl>
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
Run Code Online (Sandbox Code Playgroud)

请注意,您的year专栏是有factor格式的,这很难处理。我建议您numeric在创建数据框时保持年份列的格式。请看下面的例子。如果删除年份列中的引号。你不需要mutate(year = as.numeric(as.character(year)))你的代码。

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)