简体   繁体   中英

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.

Ie 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)

样本数据

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM