0

I have Days in a dataset and I want to show the next 5 days based on the last date in dataset but skipping weekend using R code.

Below I have generated the next 5 days date and but when unable to skip weekend.

lastValue = tail(dataset$Days,1)
> lastValue+1:5
[1] "2017-07-14" "2017-07-15" "2017-07-16" "2017-07-17" "2017-07-18"

If I use Chron function I can remove weekend but how to show 2 more date which removed because of weekend as I need to show 5 days date.

dataset [!chron::is.weekend(as.Date(dataset $Days, "%m/%d/%Y")), ]

[1] "2017-07-14" "2017-07-17" "2017-07-18"

Thanks

DevRj
  • 448
  • 8
  • 19
  • Related: [Adding 15 business days in lubridate](https://stackoverflow.com/questions/26749336/adding-15-business-days-in-lubridate) – Henrik Jul 30 '17 at 19:59
  • Please check out the [Markdown help](https://stackoverflow.com/editing-help) and put your code examples in code blocks. – Scott Colby Jul 30 '17 at 19:59

1 Answers1

2

There is always one Sat and one Sun in each 7 consecutive day period so generate the next 7 values and then remove the weekend and we will necessarily have 5 days left.

library(chron)

lastValue <- as.Date("2017-07-13")

next7 <- lastValue + 1:7
next7[!is.weekend(next7)]
## [1] "2017-07-14" "2017-07-17" "2017-07-18" "2017-07-19" "2017-07-20"

If we later decide that we want the next three days, say, then we can't just take the next 5 and remove weekends since the number of Sat and Sun days in 5 consecutive days can be 0, 1, or 2 so instead use 5 but then take the first 3 of what is left after removing weekend days.

next5 <- lastValue + 1:5
head(next5[!is.weekend(next5)], 3)
## [1] "2017-07-14" "2017-07-17" "2017-07-18"
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341