Search code examples
rdatetimeif-statementdplyrcase-when

Add new column using case_when of other column in R


I want to add a column to my data frame which takes values such as "mon", "tue", "wed", "thu" etc. depending on another column containing a "date time" variable, but I can't use the weekdays function as it also depends on the time of the day.

I.e. if the column created_at is between: 2021-03-01 09:00:00 and 2021-03-02 09:00:00 then the new column should classify as "mon".

If on the other hand the created_at is between 2021-03-02 09:00:00 and 2021-03-03 09:00:00 it should classify as "tue".

And so on for the rest of the week. (following the hours of the stock market)

Sample data


Solution

  • This should work:

    library(lubridate)
    library(dplyr)
    
    df %>%
      mutate(
        result = wday(created_at - hours(9), label = TRUE)
      )
    

    If you have issues, please post a reproducible sample of data using dput().