Home > Software design >  Ifelse with date
Ifelse with date

Time:10-16

Trying to produce an output that tests if date_1 is in AM or PM. This is the code I have but it is not working. If the date is AM I want the "It is in AM", if not, I want the output, "It is the PM"

date_1 <- as.Date("2021/05/25 14:34:25")

ifelse(date_1 == AM, "It is in the AM","It is the PM" )

CodePudding user response:

Your date is a date time object.

With lubridate ...

library(lubridate, warn = FALSE)

dt_1 <- ymd_hms(c("2021/05/25 14:34:25", "2021/05/25 00:34:25"))

ifelse(am(dt_1), "It is in the AM","It is the PM" )
#> [1] "It is the PM"    "It is in the AM"

A base R option ...

dt_1 <- as.POSIXlt(c("2021/05/25 14:34:25", "2021/05/25 00:34:25"))

ifelse(dt_1$hour >= 0 & dt_1$hour < 12, "It is in the AM","It is the PM" )
#> [1] "It is the PM"    "It is in the AM"

Created on 2022-10-15 with reprex v2.0.2

  •  Tags:  
  • r
  • Related