lubridate和ifelse

时间:2013-03-15 15:50:52

标签: r lubridate

更新:澄清了回答评论者的问题和代码。

我不知道为什么date.ie创建了一个POSIXct对象,但date.ipt创建了一个数字对象。在这两种情况下,我都使用lubridate来添加日期。

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

更新2:

下一个块是我的旧方法,由于ifelse的行为方式,它无法正常工作。谢谢@hadley指出这一点。

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")

这是我的修复。而不是使用ifelse一步创建date.ipt,我在几个中做。我到达了我想去的地方,但需要一段时间。希望评论者能够提出如何更有效地做到这一点的建议。

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)

0 个答案:

没有答案