简体   繁体   English

使用 R 中其他列的 case_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.我想根据包含“日期时间”变量的另一列,在我的数据框中添加一个列,该列采用“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.

相关问题 根据从不同列获得的值创建新列,使用 R 中的 mutate() 和 case_when 函数 - Creating a new column based on values obtained from different column, using mutate() and case_when function in R 在 case_when 中使用 for 循环根据 R 中的某个条件添加新列 - Use a for loop inside a case_when to add a new column based on a certain condition in R 使用 case_when 和 %in% 运算符创建新列在 R 中返回 NA? - Creating a new column using case_when and %in% operator returns NA in R? R 使用 case_when 按组跟踪列中的更改 - R Using case_when to track changes in a column by group 在dplyr中使用case_when更改新列时遇到问题 - Trouble mutating new column using case_when in dplyr 在 Dplyr 中使用 case_when 创建新列时遇到问题 - Trouble making a new column using case_when in Dplyr 使用 R function 使用变量/列名称作为 arguments 使用 mutate 和 case_when 创建新变量时出错 - errors when using R function using variables/column names as arguments to create a new variable using mutate and case_when 使用 case_when() 和 filter() 根据 R 中一列中的值和另一列中的级别对数​​据框进行子集化 - using case_when() and filter() to subset a dataframe based on values in one column and levels in another column in R R:基于字符串替换列值的有效方法(可能使用 case_when 或某种其他形式的 mutate)? - R: Efficient way to replace column values based on strings (maybe with case_when or some other form of mutate)? 从 R 的数据框中的现有列创建新的竞争变量(使用 case_when 函数) - Creating a New Race Variable from Existing Column in Data Frame in R (with case_when function)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM