Reputation: 1
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
Upvotes: 0
Views: 78
Reputation: 269471
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"
Upvotes: 2