I have the following:
df <- data.frame(A = c(1:8), ref.date = c(NA, "10/12/18", NA, NA, "12/15/19", NA, NA, NA))
df$ref.date <- as.Date(df$ref.date, format = "%m/%d/%y")
df$new.date <- NA
I would like to update new.date such that for any given row, new.date is equal to ref.date if ref.date is not NA, and is equal to the value of new.date in the previous row if ref.date is NA. So the result would be:
A ref.date new.date
1 <NA> NA
2 10/12/18 10/12/18
3 <NA> 10/12/18
4 <NA> 10/12/18
5 12/15/19 12/15/19
6 <NA> 12/15/19
7 <NA> 12/15/19
8 <NA> 12/15/19
I tried
library(dplyr)
df <- df %>% mutate(new.date = ifelse(is.na(ref.date), lag(new.date), ref.date))
df$new.date <- as.Date(df$new.date, format = "%m/%d/%y")
But this yielded dates in numeric format and did not fill rows correctly where ref.date is NA.