find一个星期的一天

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

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

R有没有办法在date中添加与星期几相关的另一列? 数据集非常大,因此手动进行更改是没有意义的。

 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 

这可能吗? 任何人都可以指向我的包,这将允许我这样做? 只是试图自动生成date的一天。

 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组件是星期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" 

查找?strftime

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

使用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 

假设您还希望星期一星期一开始(而不是在星期天默认),那么以下内容将有所帮助:

 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 

这应该做的伎俩

 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 

格式为JStrahl format(as.Date(df$date),"%w")注释format(as.Date(df$date),"%w") ,我们得到当天的数字: as.numeric(format(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