Error: Problem with `mutate()`

#>  I want to create a column that will identify the time of the day (Morning, Afternoon, Evening) based on the  variable time. 

day_time <- tibble(football)%>%
mutate(time_of_day = if (time >= hms("06:00") & time<= hms("12:00") ){print ("Morning")}
       else if (time> hms("12:00") & time<= hms("18:00")){print("Afternoon")}
       else {print ("Evening")}
)
       day_time

I am getting this error message:

Error: Problem with mutate() column time_of_day.
i time_of_day = if (...) NULL.
x missing value where TRUE/FALSE needed
Run rlang::last_error() to see where the error occurred.
In addition: Warning messages:
1: Problem with mutate() column time_of_day.
i time_of_day = if (...) NULL.
i Some strings failed to parse, or all strings are NAs
2: Problem with mutate() column time_of_day.
i time_of_day = if (...) NULL.
i Some strings failed to parse, or all strings are NAs
3: Problem with mutate() column time_of_day.
i time_of_day = if (...) NULL.
i the condition has length > 1 and only the first element will be used

I think there may be a couple errors happening here, but at least one is that hms() is not parsing the times as they're written here: It expects to have seconds included, and the times only have hours and minutes.

Additionally, I find case_when() easier to use in these scenarios than if() statements. So what you're trying to accomplish could be done like so:

library(tidyverse)
library(lubridate)

# Sample data I created that may be similar to yours
football <- tibble(time = hm(c("05:00", "11:00", "16:00")))

football %>%
  mutate(time_of_day = case_when(time >= hm("06:00") & time <= hm("12:00") ~ "Morning",
                                 time > hm("12:00")  & time <= hm("18:00") ~ "Afternoon",
                                 TRUE                                      ~ "Evening"))

Hope this helps!

Thank you. This helps a lot.

This topic was automatically closed 21 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.