user3672037
user3672037

Reputation: 29

If date is on Sunday, then change date to the following Monday

Sunday date in mydates is 2018-05-06. I would like 1 day added so that 2018-05-06 becomes 2018-05-07 (Monday). That is, if a date falls on a Sunday add one day.

library(dplyr)
library(lubridate)

mydates <- as.Date(c('2018-05-01','2018-05-02','2018-05-05','2018-05-06'))

# find which are weekend dates
x = as.character(wday(mydates,TRUE))

if(x == 'Sun') { mydates + 1 }                  

# the Sunday date in mydates is 2018-05-06.  I would like 1 day added so 
that 2018-05-06 becomes 2018-05-07

Here's my error: Warning message: In if (x == "Sun") { : the condition has length > 1 and only the first element will be used

Upvotes: 0

Views: 57

Answers (3)

janverkade
janverkade

Reputation: 144

First, identify which of your dates are Sundays. Then, selectively add 1

library(lubridate)
mydates <- as.Date(c('2018-05-01','2018-05-02','2018-05-05','2018-05-06'))

i <- which(as.character(wday(mydates,TRUE))=="Sun")
mydates[i] <- mydates[i]+1

this outputs

 "2018-05-01" "2018-05-02" "2018-05-05" "2018-05-07"

which, I believe, is the desired result.

Upvotes: 0

GordonShumway
GordonShumway

Reputation: 2056

X is a vector so you can use anif_else statement to increment the Sundays as follows:

library(dplyr)
library(lubridate)
new_dates <- if_else(x == 'Sun', mydates + days(1), mydates)

Upvotes: 0

Rui Barradas
Rui Barradas

Reputation: 76402

Try ifelse. Then convert to class Date.

as.Date(ifelse(x == 'Sun', mydates + 1, mydates), origin = '1970-01-01')
#[1] "2018-05-01" "2018-05-02" "2018-05-05" "2018-05-07"

Upvotes: 1

Related Questions