Search code examples
rdplyrnested-loopsfacebook-prophet

Exclude Weekends in Dot in Dplyr


This is a continuation question from this answer: https://stackoverflow.com/a/45254762/5893585

I am using the do function in dplyr within the prophet package. When attempting this I want to make a future dataframe with weekends excluded. Below is my current code:

Current dataframe:

dataset
          ds     group     y
  2021-12-15         A     5
  2021-12-16         A     6
  2021-12-15         B    10
  2021-12-16         B     7
         etc       etc   etc

Prediction

library(dplyr)
library(prophet)

data = dataset %>%  
group_by(group) %>%
do(predict(prophet(., daily.seasonality = TRUE, yearly.seasonality = TRUE), 
make_future_dataframe(prophet(.,daily.seasonality = TRUE, yearly.seasonality = TRUE), periods = 14))) %>%
select(ds, group, yhat)

How do I rewrite the above code to filter for the make_future_dataframe dataset not have weekends?

I want it to looks something like this, however this is not working:

data = dataset %>%  
  group_by(group) %>%
  do(predict(prophet(., daily.seasonality = TRUE, yearly.seasonality = TRUE), 
  make_future_dataframe(prophet(.[which(weekdays(.$ds) != 'Saturday' | weekdays(.$ds) != 'Sunday'),],daily.seasonality = TRUE, yearly.seasonality = TRUE), periods = 14))) %>%
  select(ds, group, yhat)

Solution

  • We could remove weekend days prior to predict:

    df %>% 
      group_by(group) %>% 
      mutate(weekdays = weekdays(ds)) %>% 
      filter(weekdays != "Saturday" & weekdays != "Sunday") %>% 
      do(predict(prophet(., daily.seasonality = TRUE, yearly.seasonality = TRUE), 
      filter(make_future_dataframe(prophet(., daily.seasonality = TRUE, yearly.seasonality = TRUE), periods = 14), weekdays(ds) != "Saturday" & weekdays(ds) != "Sunday"))) %>%
      select(ds, group, yhat)