0

I am reading in an excel file in R and calculating the date 6 months prior to the date. If the date is falls on Weekend, need to change the date to the following weekday.

for example: if date is 2020-2-7, the six months prior is 2019-08-11. Which is Sunday. How do I change the date to 2019-08-12?

I tried the following code:

date <- as.date.character("2020-2-7")
nxtd <- date-180
if(weekdays(nxtd)=="Saturday"){nxtd <- date-182} else if(weekdays(nxtd)=="Sunday"){nxtd <- date-181}
else{nxtd <- date-180}

this code gives an error/warning " the condition has length > 1 and only the first element will be used"

How do I resolve it?

JKJ
  • 204
  • 3
  • 12
  • If you want to check that a value is in a vector, you can use `%in%`. `==` checks that two things are equal. `if / else` structures in R aren't vectorized, which is why you get the warning (not error)—the condition will only be checked against the first value. Use the vectorized `ifelse`. In this case, doesn't really matter since your example has only 1 value, but I imagine your real data has more. You're also missing 2 closing quotation marks. – camille Feb 11 '20 at 16:52
  • My real data has about 50 rows of data. – JKJ Feb 11 '20 at 17:49
  • That's what I figured, which is why you'll want to switch to `ifelse`. That warning is discussed [here](https://stackoverflow.com/q/14170778/5325862). Also, you're assuming 6 months is exactly 180 days—is that really what you want? – camille Feb 11 '20 at 18:27
  • @camille, thanks, yea, I need to stick with 180 days. – JKJ Feb 11 '20 at 18:58

1 Answers1

0
library(lubridate)
d1 = as.Date("2020-2-9")
d2 = d1 - 180
if(weekdays(d2) %in% c("Saturday", "Sunday")){
    floor_date(d2 - 3, "week") + 8
} else {
    d2
}
d.b
  • 32,245
  • 6
  • 36
  • 77
  • 1
    This will only work when you have a single date, when you have multiple dates, the error of "the condition has length > 1 and only the first element will be used" remains. – JKJ Feb 11 '20 at 17:48
  • Could you explain the subtract 3 and add 8 operations? – camille Feb 11 '20 at 18:28