1
我正在尋求兩個特定的幫助點 1)如何創建一個列表給定我的數據庫(all.df)的列表 2)如何矢量化這個列表上的功能如何創建列表並向其執行矢量化函數
我試圖在使用Prophet庫的客戶/產品級別生成預測。我正在努力引導操作。 我目前運行一個for循環,我想避免並加速我的計算。
數據進行了分析
set.seed(1123)
df1 <- data.frame(
Date = seq(dmy("01/01/2017"), by = "day", length.out = 365*2),
Customer = "a",
Product = "xxx",
Revenue = sample(1:100, 365*2, replace=TRUE))
df2 <- data.frame(
Date = seq(dmy("01/01/2017"), by = "day", length.out = 365*2),
Customer = "a",
Product = "yyy",
Revenue = sample(25:200, 365*2, replace=TRUE))
df3 <- data.frame(
Date = seq(dmy("01/01/2017"), by = "day", length.out = 365*2),
Customer = "b",
Product = "xxx",
Revenue = sample(1:100, 365*2, replace=TRUE))
df4 <- data.frame(
Date = seq(dmy("01/01/2017"), by = "day", length.out = 365*2),
Customer = "b",
Product = "yyy",
Revenue = sample(25:200, 365*2, replace=TRUE))
all.df <- rbind(df1, df2, df3, df4)
這是我的預測功能
daily_forecast <- function(df, forecast.days = 365){
# fit actuals into prophet
m <- prophet(df,
yearly.seasonality = TRUE,
weekly.seasonality = TRUE,
changepoint.prior.scale = 0.55) # default value is 0.05
# create dummy data frame to hold prodictions
future <- make_future_dataframe(m, periods = forecast.days, freq = "day")
# run the prediction
forecast <- predict(m, future)
### Select the date and forecast from the model and then merge with actuals
daily_fcast <- forecast %>% select(ds, yhat) %>% dplyr::rename(Date = ds, fcast.daily = yhat)
actual.to.merge <- df %>% dplyr::rename(Date = ds, Actual.Revenue = y)
daily_fcast <- merge(actual.to.merge, daily_fcast, all = TRUE)
}
目前,我在同一時間通過一個客戶/產品配合使用for循環
x <- df1 %>% select(-c(Customer, Product)) %>%
dplyr::rename(ds = Date, y = Revenue) %>%
daily_forecast()
我想不是,vectorise整個操作:
1 - 創建名單列表,即通過拆分all.df:
一)產品,然後
二)客戶
2,然後請有上述
在列表1中創建的列表中daily_forecast功能圖)我非常喜歡使用功能出purrr
。
謝謝!愛你的第二個解決方案,它非常優雅,並有自然流動。我希望我可以多次投票答覆這個答案! – cephalopod