Reputation: 29
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
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
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
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