To generate the output below, I am using the following code:
safe.ifelse <- function(cond, yes, no) structure(ifelse(cond, yes, no), class = class(yes))
library(lubridate)
df <- data.frame(i_date=mdy("9/1/2011") + months(seq(0,31)), t_date=mdy("2/1/2012")) r <- seq(1:nrow(df))
r <- (r - which(df$i_date == df$t_date)) %/% 12
df$r_date <- as.Date(safe.ifelse(r<0, df$i_date, df$t_date + years(r)), origin = "1970-01-01")
For good reason, I get an error if I set the t_date to be beyond the biggest i_date. Does anyone know a way to avoid this error? So instead of finding where the i_date and t_date match, replicating the t_date 12 times and adding a year, replicating again 12 times etc, I would just cascade the i_date the entire way to the end of the r_date where all three columns of the data frame have the same length. So in the case I am referring to, the i_date would match the t_date if the t_date is > max(i_date) otherwise we would do what we see below. Thanks!
i_date t_date r_date
9/1/2011 2/1/2012 9/1/2011
10/1/2011 2/1/2012 10/1/2011
11/1/2011 2/1/2012 11/1/2011
12/1/2011 2/1/2012 12/1/2011
1/1/2012 2/1/2012 1/1/2012
2/1/2012 2/1/2012 2/1/2012
3/1/2012 2/1/2012 2/1/2012
4/1/2012 2/1/2012 2/1/2012
5/1/2012 2/1/2012 2/1/2012
6/1/2012 2/1/2012 2/1/2012
7/1/2012 2/1/2012 2/1/2012
8/1/2012 2/1/2012 2/1/2012
9/1/2012 2/1/2012 2/1/2012
10/1/2012 2/1/2012 2/1/2012
11/1/2012 2/1/2012 2/1/2012
12/1/2012 2/1/2012 2/1/2012
1/1/2013 2/1/2012 2/1/2012
2/1/2013 2/1/2012 2/1/2013
3/1/2013 2/1/2012 2/1/2013
4/1/2013 2/1/2012 2/1/2013
5/1/2013 2/1/2012 2/1/2013
6/1/2013 2/1/2012 2/1/2013
7/1/2013 2/1/2012 2/1/2013
8/1/2013 2/1/2012 2/1/2013
9/1/2013 2/1/2012 2/1/2013
10/1/2013 2/1/2012 2/1/2013
11/1/2013 2/1/2012 2/1/2013
12/1/2013 2/1/2012 2/1/2013
1/1/2014 2/1/2012 2/1/2013
2/1/2014 2/1/2012 2/1/2014
3/1/2014 2/1/2012 2/1/2014
4/1/2014 2/1/2012 2/1/2014