0

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

Henrik
  • 65,555
  • 14
  • 143
  • 159
  • x and mydates are vectors... no reason to use x == "Sun" or mydates + 1... you can use for loop.. – Ika8 Oct 30 '18 at 17:13

3 Answers3

1

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"
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
0

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)
GordonShumway
  • 1,980
  • 13
  • 19
  • 2
    `if_else` is from `dplyr`...you should mention that...anyways `ifelse` should also be fine here... – Shree Oct 30 '18 at 17:37
  • @Shree Not really. See [How to prevent ifelse() from turning Date objects into numeric objects](https://stackoverflow.com/questions/6668963/how-to-prevent-ifelse-from-turning-date-objects-into-numeric-objects) – Henrik Oct 30 '18 at 17:49
  • Shree, the dplyr package was imported in the question but I updated my answer to make it complete – GordonShumway Oct 30 '18 at 17:52
  • @Henrik...interesting! I wasn't aware of that `ifelse` behavior. – Shree Oct 30 '18 at 17:54
  • @GordonShumway...makes sense...I hadn't noticed `dplyr` in the question I guess... – Shree Oct 30 '18 at 17:57
0

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.

janverkade
  • 124
  • 1
  • 8