I have a dataframe where the first 5 columns are boolean, and the next 2 columns are a start and end date. Where the first 5 columns are equal to 1, I would like to transmute such that they are then assigned a date between the start and end dates. The 0 values can be left as 0.
Example dataframe:
df<- data.frame(A = c(1,1,0,0,1), B = c(0,1,0,0,1), C = c(0,0,1,1,0),D = c(1,0,0,0,1), E = c(1,1,1,0,0),
StartDate = as.Date(c("2018-03-21","1999-02-06","2004-01-19", "2000-03-18", "1998-05-20")),
EndDate = as.Date(c("2020-08-02","2004-09-15","2009-07-27","2017-04-21", "2001-01-24"))
> A B C D E StartDate EndDate
1 0 0 1 1 2018-03-21 2020-08-02
1 1 0 0 1 1999-02-06 2004-09-15
0 0 1 0 1 2004-01-19 2009-07-27
0 0 1 0 0 2000-03-18 2017-04-21
1 1 0 1 0 1998-05-20 2001-01-24
I would like an output where each of the 1 values are replaced by a random date between the StartDate and EndDate for each row, e.g:
> A B C D E StartDate EndDate
2019-07-22 0 0 2020-01-30 2018-03-26 2018-03-21 2020-08-02
1999-03-21 2002-04-04 0 0 1999-09-14 1999-02-06 2004-09-15
0 0 2005-06-07 0 2008-05-28 2004-01-19 2009-07-27
0 0 2015-10-11 0 0 2000-03-18 2017-04-21
1999-02-05 2000-11-14 0 1999-12-19 0 1998-05-20 2001-01-24
So far I am thinking along the lines of:
For .vars = 1:5, run an ifelse() where any 1 value is replaced by a random date between StartDate and EndDate
df %>%
transmute_at(.vars = 1:5,
.funs = ifelse(1,sample(seq(StartDate, EndDate, by = "day"), 1), 0) )
This however doesn't run as it cannot find StartDate and EndDate due to the code only running for cols 1:5
Any help would be appreciated!