I've got dataframe like so:
id year
001 1988
001 1988
001 1988
001 1988
001 1988
002 1972
002 1972
002 1972
002 1972
For each id
, I would like to convert the variable year
into a sequence beginning from the first observation, increasing by one in each consecutive row. The desired output:
id year
001 1988
001 1989
001 1990
001 1991
001 1992
002 1972
002 1973
002 1974
002 1975
How do I do this? A tidyverse
solution would be preferred. Thanks.
My data:
df <- data.frame(id = c("001", "001", "001", "001", "001", "002", "002", "002", "002"),
year = c(1988, 1988, 1988, 1988, 1988, 1972, 1972, 1972, 1972))
With seq
:
library(dplyr)
df %>%
mutate(year = seq(first(year), length.out = n()), .by = id)
# id year
# 1 1 1988
# 2 1 1989
# 3 1 1990
# 4 1 1991
# 5 1 1992
# 6 2 1972
# 7 2 1973
# 8 2 1974
# 9 2 1975