我需要创建一个变量,告诉我自第一次观察特定组以来的年数, 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 变量为0,用于第一次观察每个冲突。基本上,我需要的是一种设置每个 conflictID 第一年的基准日期的方法,如果这是有意义的吗?
答案 0 :(得分:3)
我们可以使用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
请注意,您的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)
答案 1 :(得分:3)
基地R中的一行...
df$year <- as.numeric(as.character(df$year)) #your years are factors
df$duration <- df$year - ave(df$year, df$conflictID, FUN=min)
df
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
答案 2 :(得分:3)
data.table
library(data.table)
setDT(df)[, duration := year - min(year), conflictID]
df
# 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