基于条件语句向POSIXct添加时间

时间:2016-12-12 21:31:27

标签: r

我有下面的数据框

如果时间3是12,那么我想加1小时到时间2。当我这样做时,结果返回数字而不是POSIXct。我怎样才能做到这一点?

dat = data.frame(
  time1 = as.POSIXct(c("2016-01-01 00:00:00")), 
  time2 =as.POSIXct(c("2016-02-02 10:10:10")) ,
   time3 =as.POSIXct(c("2016-02-02 12:30:30")) 
  ) 
dat
class(dat$time1)
class(dat$time2)
dat$test = ifelse(as.numeric(format(dat$time3, format = "%H") ) == 12, dat$time2+3600, dat$time1)
dat

1 个答案:

答案 0 :(得分:1)

以下是一些替代方案:

1)替换

transform(dat, test = replace(time1, as.POSIXlt(time3)$hour == 12, time2 + 3600))

2)算术

transform(dat, test = time1 + (as.POSIXlt(time3)$hour == 12) * (time2 - time1 + 3600))

2)dplyr :: if_else

dat %>% mutate(test = if_else(as.POSIXlt(time3)$hour == 12, time2 + 3600, time1))