-1

I am trying to pass an if-else statement in R where I am looking at the time in the column. I want to create a column called "after hours" where I will look at the time from another column. If the time falls between 8am and 5pm then it is not after hours but if it falls after 5pm and before 8 am then it is after hours.

my table looks something like this

date time
01/01/2022 7:34 AM
01/02/2022 14:54 PM
01/03/2022 17:59 PM

And when I create the "after hours" column it should look something like this

date time after hours
01/01/2022 7:34 AM Yes
01/02/2022 14:54 PM No
01/03/2022 17:59 PM Yes

I tried this if else statement but I keep getting an error

dplyr::mutate(intake_received_after_hours=ifelse(intake_time=between("17:01" & "7:59")), yes, no)

Error: Problem with mutate() input intake_received_after_hours. x unused argument (intake_time = between("17:01" & "7:59")) i Input intake_received_after_hours is ifelse(intake_time = between("17:01" & "7:59")).

  • 1
    It will be easier to help you with your specific question if you include a code sample to create your sample data. In any case, the `between` function in R that takes a from and to parameter and returns a boolean should cover what you need. – geoff Jan 12 '22 at 19:39
  • 1
    Can you show what you've tried and where you fail? It would also be nice if you gave your examples in an easy-to-paste manner. More info on that here: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Roman Luštrik Jan 12 '22 at 19:39
  • 1
    Your first two columns are strings, they have nothing to do with dates or times. If you want numeric "between" comparisons, then you need to convert into something number-like. In this case, see https://stackoverflow.com/q/67548644/3358272 for one way to convert time-like strings into number-like things (without dates). (One could also use the `lubridate` package for similar purposes.) – r2evans Jan 12 '22 at 19:40

1 Answers1

0

You can try this using hm from lubridate and some logical conditioning.

library(dplyr)
library(lubridate)

df %>% 
  mutate('after hours'=ifelse(
    hm(time) > hm("8:00") & 
    hm(time) < hm("17:00"), "No", "Yes"))
        date     time after hours
1 01/01/2022  7:34 AM         Yes
2 01/02/2022 14:54 PM          No
3 01/03/2022 17:59 PM         Yes
Andre Wildberg
  • 12,344
  • 3
  • 12
  • 29