1
votes

I have the below dataframe and i want to create the 'create_col' using some kind of seq() function i guess using the 'year' column as the start of the sequence. How I could do that?

id <- c(1,1,2,3,3,3,4)
year <- c(2013, 2013, 2015,2017,2017,2017,2011)
create_col <- c(2013,2014,2015,2017,2018,2019,2011)

Ideal result:

  id year create_col
1  1 2013       2013
2  1 2013       2014
3  2 2015       2015
4  3 2017       2017
5  3 2017       2018
6  3 2017       2019
7  4 2011       2011


1

1 Answers

1
votes

You can add row_number() to minimum year in each id :

library(dplyr)

df %>%
  group_by(id) %>%
  mutate(create_col = min(year) + row_number() - 1)

#    id  year create_col
#  <dbl> <dbl>      <dbl>
#1     1  2013       2013
#2     1  2013       2014
#3     2  2015       2015
#4     3  2017       2017
#5     3  2017       2018
#6     3  2017       2019
#7     4  2011       2011

data

df <- data.frame(id, year)