FlyingDutch
FlyingDutch

Reputation: 1152

maintain POSIXct time format with ifelse and dplyr and return POSIXct for both true and false

I have a dummy data frame that contains 10 date time stamps in POSIXct. Now i would like to evaluate each row, replace the cell value with a different one if above a date time threshold, otherwise keep it. I found a helpful thread here using the dplyr package, but i cannot get it to work for my particular case. Any suggestions?

The code for the dummy data frame:

df<-structure(list(Date.Out = structure(c(1478699520, 1493934000, 
1510243080, 1524862800, 1541776440, 1559243220, 1475417460, 1493930940, 
1495304760, 1504640100), class = c("POSIXct", "POSIXt"), tzone = "US/Eastern")), row.names = c(6L, 
7L, 8L, 9L, 10L, 11L, 15L, 16L, 17L, 18L), class = "data.frame")

The code that i tried using the dplyr package that doesn't work:

df %>% 
  mutate(new =  as.POSIXct(ifelse(Date.Out>="2019-05-01 00:00:00", "2019-05-01 00:00:00", Date.Out), origin='1970-01-01', na.rm=T))

Upvotes: 1

Views: 494

Answers (1)

akrun
akrun

Reputation: 887511

Consider using case_when instead of ifelse as ifelse can coerce it to integer

library(dplyr)
df <- df %>% 
   mutate(new = case_when(Date.Out >= as.POSIXct("2019-05-01 00:00:00")
        ~ as.POSIXct("2019-05-01 00:00:00"), TRUE ~ Date.Out))

-output

df
        Date.Out                 new
6  2016-11-09 08:52:00 2016-11-09 08:52:00
7  2017-05-04 17:40:00 2017-05-04 17:40:00
8  2017-11-09 10:58:00 2017-11-09 10:58:00
9  2018-04-27 17:00:00 2018-04-27 17:00:00
10 2018-11-09 10:14:00 2018-11-09 10:14:00
11 2019-05-30 15:07:00 2019-05-01 00:00:00
15 2016-10-02 10:11:00 2016-10-02 10:11:00
16 2017-05-04 16:49:00 2017-05-04 16:49:00
17 2017-05-20 14:26:00 2017-05-20 14:26:00
18 2017-09-05 15:35:00 2017-09-05 15:35:00

Upvotes: 1

Related Questions