从日期创建因子变量“周末"和“工作日" [英] Creating factor variables 'weekend' and 'weekday' from date
本文介绍了从日期创建因子变量“周末"和“工作日"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据框.这只是头部,日期跨越2个月.我的问题是如何在数据框中创建两个级别为工作日"和周末"的新因子变量,以指示给定的日期是工作日还是周末?
I have the following dataframe. This is just the head and the dates span over a period of 2 months. My question is how can I create a new factor variable in the dataframe with two levels, "weekday" and "weekend", indicating whether a given date is a weekday or weekend day?
steps date interval
1 37.3826 2012-10-01 0
2 37.3826 2012-10-01 5
3 37.3826 2012-10-01 10
4 37.3826 2012-10-01 15
5 37.3826 2012-10-01 20
6 37.3826 2012-10-01 25
推荐答案
您可以使用 base R
df1$date <- as.Date(df1$date)
#create a vector of weekdays
weekdays1 <- c('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')
#Use `%in%` and `weekdays` to create a logical vector
#convert to `factor` and specify the `levels/labels`
df1$wDay <- factor((weekdays(df1$date) %in% weekdays1),
levels=c(FALSE, TRUE), labels=c('weekend', 'weekday')
#Or
df1$wDay <- c('weekend', 'weekday')[(weekdays(df1$date) %in% weekdays1)+1L]
或者 isWeekday
, isWeekend
来自 timeDate
.我们可以使用 wday
参数指定工作日
.它返回一个逻辑向量,并且如果我们需要转换为如上所述的可能的字符串.
Or isWeekday
, isWeekend
from timeDate
. We can specify the weekdays
with wday
argument. It returns a logical vector, and if we need to convert to strings that can be possible as showed above.
library(timeDate)
isWeekday(df1$date, wday=1:5)
这篇关于从日期创建因子变量“周末"和“工作日"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文