计算匹配列值的第一行和 n 行之间的 duration/difference
Calculate duration/difference between first and n rows that match on column value
我正在尝试计算在一列中匹配的数据帧的第一行和 n 行之间的 difference/duration。我想将该值放在新列 "duration" 中。示例数据:如下。
y <- data.frame(c("USA", "USA", "USA", "France", "France", "Mexico", "Mexico", "Mexico"), c(1992, 1993, 1994, 1989, 1990, 1999, 2000, 2001))
colnames(y) <- c("Country", "Year")
y$Year <- as.integer(y$Year) # this is to match the class of my actual data
我想要的结果是:
1992 USA 0
1993 USA 1
1994 USA 2
1989 France 0
1990 France 1
1999 Mexico 0
2000 Mexico 1
2001 Mexico 2
我试过使用 dplyr's group_by and mutate
y <- y %>% group_by(Country) %>% mutate(duration = Year - lag(Year))
但我只能得到实际的滞后年份(例如 1999 年)或只能计算连续行之间的差异让我得到一个国家的第一行 NA 或 1同一个国家的所有其他行。 q & a's focus on difference between sequential rows 而不是第一行和 n 行之间。
想法?
这可以通过在按 'Country' 分组后用 'Year' 列减去 first
'Year' 来完成。
y %>%
group_by(Country) %>%
mutate(duration = Year - first(Year))
我正在尝试计算在一列中匹配的数据帧的第一行和 n 行之间的 difference/duration。我想将该值放在新列 "duration" 中。示例数据:如下。
y <- data.frame(c("USA", "USA", "USA", "France", "France", "Mexico", "Mexico", "Mexico"), c(1992, 1993, 1994, 1989, 1990, 1999, 2000, 2001))
colnames(y) <- c("Country", "Year")
y$Year <- as.integer(y$Year) # this is to match the class of my actual data
我想要的结果是:
1992 USA 0
1993 USA 1
1994 USA 2
1989 France 0
1990 France 1
1999 Mexico 0
2000 Mexico 1
2001 Mexico 2
我试过使用 dplyr's group_by and mutate
y <- y %>% group_by(Country) %>% mutate(duration = Year - lag(Year))
但我只能得到实际的滞后年份(例如 1999 年)或只能计算连续行之间的差异让我得到一个国家的第一行 NA 或 1同一个国家的所有其他行。
想法?
这可以通过在按 'Country' 分组后用 'Year' 列减去 first
'Year' 来完成。
y %>%
group_by(Country) %>%
mutate(duration = Year - first(Year))