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