[英]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.我想根据包含“日期时间”变量的另一列,在我的数据框中添加一个列,该列采用“mon”、“tue”、“wed”、“thu”等值,但我不能使用工作日 function 因为它也取决于一天中的时间。
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".即,如果 created_at 列介于:2021-03-01 09:00:00 和 2021-03-02 09:00:00 之间,则新列应归类为“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".另一方面,如果 created_at 介于 2021-03-02 09:00:00 和 2021-03-03 09:00:00 之间,则应归类为“tue”。
And so on for the rest of the week.以此类推为本周的 rest。 (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()
.如果您有问题,请使用
dput()
发布可重现的数据样本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.