如何将日期转换为最近的周末(星期六)

时间:2019-01-30 09:10:41

标签: r date lubridate weekend chron

我有一个日期格式为“%d-%m-%Y”的数据框,并具有星期数。日期是工作日,我希望在另一列中找到该周的星期六。

我最初使用Chron软件包中的函数检查日期是工作日还是周末,但这是布尔验证。我已经将date变量格式化为Date格式,并提取了每个日期的星期数。

df = data.frame(date=c("2014-08-20", "2014-08-25", "2014-10-08")) 
df$date=as.Date(df$date,format="%Y-%m-%d")
df$week=week(ymd(df$date))

预期结果应该是:

date        week    EOW  
2014-08-20   34   2014-08-23

2014-08-25   34   2014-08-30

2014-10-08   41   2014-10-11

4 个答案:

答案 0 :(得分:3)

Base R选项。首先创建所有天数的列表,然后用match weekdays并将其从6中减去(如我们想要的星期六),以获取需要在原始date列中添加的天数

all_days <- c("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")

#As @nicola mentioned this is locale dependent
#If your locale is not English you need weekdays in your current locale
#which you can manually write as shown above or do any one of the following

#all_days <- weekdays(seq(as.Date("2019-01-14"),by="day",length.out=7))
#OR
#all_days <- format(seq(as.Date("2019-01-14"),by="day",length.out=7), "%A")

df$EOW <- df$date + 6 - match(weekdays(df$date), all_days)

df
#        date week        EOW
#1 2014-08-20   34 2014-08-23
#2 2014-08-25   34 2014-08-30
#3 2014-10-08   41 2014-10-11

或者lubridate具有函数ceiling_date,当与unit = "week"一起使用时,它将返回下一个“星期日”,因此我们从中减去1天以获得“星期六”。

library(lubridate)
df$EOW <- ceiling_date(df$date, unit = "week") - 1

答案 1 :(得分:1)

使用

的另一种方法
country_year

答案 2 :(得分:0)

使用data.table连接语法:

library(data.table)

# Create a saturdays dataset
saturdays2014 <- data.table(date = seq(as.Date("2014-01-01"), as.Date("2014-12-31"), by = 1))
Sys.setlocale("LC_ALL","English")
saturdays2014 <- saturdays2014[weekdays(date) == "Saturday"]

# convert df to data.table and date to a Date variable
setDT(df)[, date := as.Date(date)]

# Join
df[saturdays2014, on = "date", roll = 6, EOW := i.date]
df    
#          date        EOW
# 1: 2014-08-20 2014-08-23
# 2: 2014-08-25 2014-08-30
# 3: 2014-10-08 2014-10-11

答案 3 :(得分:-1)

优化代码。这是星期六。如果要在该周的星期四进行计算,请在计算中使用“ 5”而不是“ 7”。

library(lubridate)
library(dplyr)

df <- data.table(date=as.Date(c("2019-01-04","2019-01-07", "2019-01-15", "2019-01-26","2019-01-27")))

df %>% mutate(cw = wday(date)) %>%
  mutate(nSaturday = date+(7-cw))

        date cw  nSaturday
1 2019-01-04  6 2019-01-05
2 2019-01-07  2 2019-01-12
3 2019-01-15  3 2019-01-19
4 2019-01-26  7 2019-01-26
5 2019-01-27  1 2019-02-02