How to use ifelse less/more than specific time

Hi!

I have a dataset with a time column with format equal to "%H:%M:%S". I wonder how I use e.g. ifelse statement to define a new colum which is "morning" before 09:00:00, "before dinner" from 09:01:00-12:00:00, "mid day" from 12:01:00-15:00:00 and "after dinner" from 15:01:00-18:00:00.

I tried this:
Data$TimeCat <- ifelse(Data$Time < as.POSIXct("09:01:00",format="%H:%M:%S"), "Morning", ifelse(Data$Time > as.POSIXct("09:00:00",format="%H:%M:%S") & Data$Time < as.POSIXct("12:01:00",format="%H:%M:%S") , "Before dinner", ifelse(Data$Time > as.POSIXct("12:00:00",format="%H:%M:%S") & Data$Time < as.POSIXct("15:01:00",format="%H:%M:%S") , "Mid day", ifelse(Data$Time > as.POSIXct("15:00:00",format="%H:%M:%S") & Data$Time < as.POSIXct("18:01:00",format="%H:%M:%S") , "After dinner", NA ))))

But I got this error message:
In ifelse(Data$Time < as.POSIXct("09:00:00", format = "%H:%M:%S"), :
Incompatible methods ("Ops.times", "<.POSIXt") for "<"

Does anyone have suggestion on how to solve this?

Regards Marit

Hi, I think the issue may have to do with the class of the Data$Time variable. When I try to run this code with Data$Time in POSIXct format, it runs just fine:

Data <- list(Time = c(as.POSIXct("08:00:00", format = "%H:%M:%S"),
                      as.POSIXct("12:15:00", format = "%H:%M:%S"),
                      as.POSIXct("17:30:00", format = "%H:%M:%S")))

Data$TimeCat <- ifelse(Data$Time < as.POSIXct("09:01:00",format="%H:%M:%S"), 
                  "Morning", 
                  ifelse(Data$Time > as.POSIXct("09:00:00",format="%H:%M:%S") & Data$Time < as.POSIXct("12:01:00",format="%H:%M:%S"), 
                         "Before dinner", 
                         ifelse(Data$Time > as.POSIXct("12:00:00",format="%H:%M:%S") & Data$Time < as.POSIXct("15:01:00",format="%H:%M:%S"),
                                "Mid day", ifelse(Data$Time > as.POSIXct("15:00:00",format="%H:%M:%S") & Data$Time < as.POSIXct("18:01:00",format="%H:%M:%S") , 
                                                  "After dinner", NA ))))

Data

It's good that there's a working solution.
You may prefer to use dplyr::case_when over nested if else as it is often easier syntax to follow.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.