2024-09-18 10:00:04

找出星期几

假设我在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

这可能吗?谁能给我指出一个允许我这样做的包? 试着按日期自动生成日期。


strftime:

当前地区的完整工作日名称

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

使用润滑包和功能:

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

这应该能奏效

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

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

编辑:只是为了展示另一种方式……

POSIXlt对象的wday组件是数字工作日(从星期天开始是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" 

假设你想让这一周从周一开始(而不是默认的周日),那么下面的方法是有用的:

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

form注释的JStrahl格式(as.Date(df$date),"%w"),我们得到当前日期的数字: as.numeric(格式(as.Date(“2016-05-09”)、“% w”))


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