'Fill dates in R by adding days instead of repeating the same value

I have data that looks like this where the current date value is the starting date of an event and is repeated for each round.

Event ID Round Date
101 1 2010-01-10
101 2 2010-01-10
101 3 2010-01-10
101 4 2010-01-10
102 1 2010-01-17
102 2 2010-01-17
102 3 2010-01-17
102 4 2010-01-17

This is my desired output:

Event ID Round Date
101 1 2010-01-10
101 2 2010-01-11
101 3 2010-01-12
101 4 2010-01-13
102 1 2010-01-17
102 2 2010-01-18
102 3 2010-01-19
102 4 2010-01-20

Thanks in advance for the help!

r


Solution 1:[1]

We could use seq

library(dplyr)
df1 %>% 
  group_by(EventID) %>%
  mutate(Date = seq(first(Date), length.out = n(), by = "1 day")) %>% 
  ungroup

-output

# A tibble: 8 × 3
  EventID Round Date      
    <int> <int> <date>    
1     101     1 2010-01-10
2     101     2 2010-01-11
3     101     3 2010-01-12
4     101     4 2010-01-13
5     102     1 2010-01-17
6     102     2 2010-01-18
7     102     3 2010-01-19
8     102     4 2010-01-20

Or add with row_number

df1 %>% 
   group_by(EventID) %>%
   mutate(Date = first(Date) + row_number() - 1) %>% 
   ungroup

data

df1 <- structure(list(EventID = c(101L, 101L, 101L, 101L, 102L, 102L, 
102L, 102L), Round = c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), Date = structure(c(14619, 
14619, 14619, 14619, 14626, 14626, 14626, 14626), class = "Date")), 
row.names = c(NA, 
-8L), class = "data.frame")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 akrun