Noobie Noobie - 1 month ago 12
R Question

dplyr : mutate and find next business day?

I have the following dataframe

time <- seq(from =ymd("2014-02-24"),to= ymd("2014-03-20"), by="days")
df2 <- data.frame(time)
df2 <- df2 %>% mutate(day_of_week = wday(time, label = TRUE))
> df2
time day_of_week
1 2014-02-24 Mon
2 2014-02-25 Tues
3 2014-02-26 Wed
4 2014-02-27 Thurs
5 2014-02-28 Fri
6 2014-03-01 Sat
7 2014-03-02 Sun
8 2014-03-03 Mon
9 2014-03-04 Tues
10 2014-03-05 Wed
11 2014-03-06 Thurs
12 2014-03-07 Fri
13 2014-03-08 Sat
14 2014-03-09 Sun
15 2014-03-10 Mon
16 2014-03-11 Tues
17 2014-03-12 Wed
18 2014-03-13 Thurs
19 2014-03-14 Fri
20 2014-03-15 Sat
21 2014-03-16 Sun
22 2014-03-17 Mon
23 2014-03-18 Tues
24 2014-03-19 Wed
25 2014-03-20 Thurs


Is it possible to use
dplyr
and
mutate
to get the next-business day for every date in time? Say the next Monday if time is a Friday.

lubridate
does not seem to handle business dates.

Many thanks!

Answer
library(bizdays)

load_rmetrics_calendars(2014)

mutate(df2, 
       nbd_time=following(time_seq, 'Rmetrics/NERC'),
       nbd_time=ifelse(nbd_time==time_seq, offset(time_seq, 1, 'Rmetrics/NERC'), nbd_time),
       nbd_time=as.Date(nbd_time, origin="1970-01-01"),
       nbddow=wday(nbd_time, label=TRUE))

You can define/load precise calendars that account for regional differences or specific calendar needs.