找到一周的一天

时间:2012-02-09 17:54:54

标签: r date r-faq

假设我在R中有一个日期,格式如下。

   date      
2012-02-01 
2012-02-01
2012-02-02

在R中是否有任何方法可以添加与日期相关的星期几的其他列?数据集非常大,因此手动完成并进行更改是没有意义的。

df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02")) 

因此,在添加日期之后,它最终会看起来像:

   date       day
2012-02-01   Wednesday
2012-02-01   Wednesday
2012-02-02   Thursday

这可能吗?任何人都可以指向我一个允许我这样做的包吗? 只是尝试按日期自动生成日期。

7 个答案:

答案 0 :(得分:268)

df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02")) 
df$day <- weekdays(as.Date(df$date))
df
##         date       day
## 1 2012-02-01 Wednesday
## 2 2012-02-01 Wednesday
## 3 2012-02-02  Thursday

编辑:只是为了表明另一种方式......

wday对象的POSIXlt组件是数字工作日(从星期日开始的0-6)。

as.POSIXlt(df$date)$wday
## [1] 3 3 4

可用于对工作日名称的字符向量进行子集化

c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", 
    "Friday", "Saturday")[as.POSIXlt(df$date)$wday + 1]
## [1] "Wednesday" "Wednesday" "Thursday" 

答案 1 :(得分:60)

查找?strftime

  

%A当前区域设置中的完整工作日名称

df$day = strftime(df$date,'%A')

答案 2 :(得分:50)

使用lubridate包和函数wday

library(lubridate)
df$date <- as.Date(df$date)
wday(df$date, label=TRUE)
[1] Wed   Wed   Thurs
Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat

答案 3 :(得分:17)

假设您还希望本周开始星期一(而不是星期日的默认值),那么以下内容很有帮助:

require(lubridate)
df$day = ifelse(wday(df$time)==1,6,wday(df$time)-2)

结果是区间[0,..,6]中的天数。

如果您希望间隔为[1,.. 7],请使用以下内容:

df$day = ifelse(wday(df$time)==1,7,wday(df$time)-1)

......或者:

df$day = df$day + 1

答案 4 :(得分:12)

这应该可以解决问题

df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02")) 
dow <- function(x) format(as.Date(x), "%A")
df$day <- dow(df$date)
df

#Returns:
        date       day
1 2012-02-01 Wednesday
2 2012-02-01 Wednesday
3 2012-02-02  Thursday

答案 5 :(得分:4)

start = as.POSIXct("2017-09-01")
end = as.POSIXct("2017-09-06")

dat = data.frame(Date = seq.POSIXt(from = start,
                                   to = end,
                                   by = "DSTday"))

# see ?strptime for details of formats you can extract

# day of the week as numeric (Monday is 1)
dat$weekday1 = as.numeric(format(dat$Date, format = "%u"))

# abbreviated weekday name
dat$weekday2 = format(dat$Date, format = "%a")

# full weekday name
dat$weekday3 = format(dat$Date, format = "%A")

dat
# returns
    Date       weekday1 weekday2  weekday3
1 2017-09-01        5      Fri    Friday
2 2017-09-02        6      Sat    Saturday
3 2017-09-03        7      Sun    Sunday
4 2017-09-04        1      Mon    Monday
5 2017-09-05        2      Tue    Tuesday
6 2017-09-06        3      Wed    Wednesday

答案 6 :(得分:3)

形成JStrahl format(as.Date(df$date),"%w")的评论,我们得到当天的数量: as.numeric(format(as.Date("2016-05-09"),"%w"))