简体   繁体   中英

Get next Wednesday date after a date with R

i have an assignment for students and I would like to add a column to this table that includes the date of the Wednesday following the date specified in column date . Students are supposed to look at news coverage on the day specified in date and then present their results on the next class, the next Wednesday.

#generate all possible days 
dates<-seq.Date(from=as.Date('2019-09-11'), to=as.Date('2019-10-31'), by='days')
#These are the group names
groups<-paste('Group', seq(1,6,1))
#sample 6 random dates and pair with a group
df<-data.frame(date=sample(dates, 6), group=groups)
df
d = c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
df$date + (4 - match(weekdays(df$date), d)) %% 7
#[1] "2019-10-30" "2019-10-30" "2019-09-25" "2019-10-02" "2019-09-18" "2019-10-09"

You can create the date of next Wednesday using lubridate and a vector of date difference ( date_diff ) to the next Wednesday for each weekday ( wday() ) in a custom function the following way:

next_wed <- function(x) {

  date_diff <- c(3:1,7,6:4) 

  x + date_diff[lubridate::wday(x)]

}

df$next_wednesday <- next_wed(df$date)

Update

Below is a broader solution, a function that calculates the next weekday specified as 1 = Sunday to 7 = Saturday.

next_wday <- function(d, w) {

  d + (seq(w - 1, length = 7) %% 7 + 1L)[8 - lubridate::wday(d)] 

}

The next Wednesday can be found with:

df$next_wed <- next_wday(df$date, 4)

I did this with ceiling_date()

library(lubridate)
#This sets the start day of the week to be Wednesday (7 is the default, Sunday)
options(lubridate.week.start=3)
#This assigns each day in df$date to the next unit above it and stores it as df$presentation.
df$presentation<-as.character(ceiling_date(as.Date(df$date), unit=c('week')))
#Restore default
options(lubridate.week.start=7)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM