Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ifelse with date

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading