1

I have the data frame below

If the hour of time3 is 12 then I'd like to add 1 hour to time2. When I do that the result comes back numeric and not a POSIXct. How can I make this work?

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
user3022875
  • 8,598
  • 26
  • 103
  • 167

1 Answers1

1

Here are some alternatives:

1) replace

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

2) arithmetic

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))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341