UPDATE: Clarified the question and code in response to the comment.
I do not see why date.ie creates a POSIXct object, but date.ipt creates a numeric object. In both cases, I use lubridate to add days to the date.
set.seed(34859) date.ie = (ymd("2013/07/01", tz="Africa/Nairobi")) + days(round(runif(10)*(150), digits=0)) # creates this POSIXct object # structure(c(1382821200, 1373922000, 1385326800, 1385154000, 1381093200, # 1381870800, 1372971600, 1377982800, 1382216400, 1383512400), class = c("POSIXct", # "POSIXt"), tzone = "Africa/Nairobi") date.ie <- format(date.ie, format="%Y-%m-%d") # creates this character object # c("2013-10-27", "2013-07-16", "2013-11-25", "2013-11-23", "2013-10-07", # "2013-10-16", "2013-07-05", "2013-09-01", "2013-10-20", "2013-11-04" # ) date.ie2 <- ymd(date.ie) treat <- rep(0:1, 5) start.ipt <- (sample(x=c(0,1), size=10, replace=TRUE, prob=c(.5, .5))) # changed to even prob for small dataset
Update 2:
This next snippet was my old approach, and it didn’t work due to how ifelse behaves. Thanks, @hadley, for that.
date.ipt <- ifelse(treat==0 & start.ipt==1, date.ie2 + days(round(runif(10)*(90), digits=0)), ifelse(treat==1 & start.ipt==1, date.ie2 + days(round(runif(100)*(60), digits=0)),NA)) # creates this numeric object # c(1384992000, 1375488000, NA, NA, NA, 1385337600, 1375142400, # 1381449600, 1383782400, 1384560000) date.ipt = format(data$date.ipt, format="%Y-%m-%d")
Here is my fix. Instead of using ifelse to create date.ipt in one step, I do it in several. I get to where I want to be, but it takes time. We hope that commentators will have suggestions on how to do this more effectively.
date.ipt.c <- date.ie2 + days(round(runif(10)*(90), digits=0)) date.ipt.c = format(date.ipt.c, format="%Y-%m-%d") date.ipt.t <- date.ie2 + days(round(runif(10)*(60), digits=0)) date.ipt.t = format(date.ipt.t, format="%Y-%m-%d") date.ipt <- ifelse(treat==1 & start.ipt==1, date.ipt.t, ifelse(treat==0 & start.ipt==1, date.ipt.c, NA)) date.ipt <- format(date.ipt, format="%Y-%m-%d") date.ipt2 <- ymd(date.ipt) days.to.ipt <- difftime(date.ipt2, date.ie2, tz="Africa/Nairobi", units="days") data <- data.frame(date.ie, treat, start.ipt, date.ipt, days.to.ipt)