按星期平均移动平均值

时间:2017-08-17 16:07:34

标签: r forecasting

Quick R问题:我有一个看起来像这样的数据集:

Outlet        weekday    visitors   Month
jackInthebox    Monday  10          July      
jackInthebox    Monday  11          July       
jackInthebox    Tues    15          July
jackInthebox    Tues    16          July 
jackInthebox    Wed     30          July
jackInthebox    Wed     28          July 
KFC             Monday  50          July 
KFC             Monday  53          July 
KFC             Tues    60          July 
KFC             Tues    64          July
KFC             Wed     30          July
KFC             Wed     31          July

我想做一个移动平均线预测,但是按星期几和网点排序。因此,请在接下来的5个星期一以及接下来的5个星期二等获得jackinthebox的预测,依此类推。这适用于每个插座。并希望添加一个插座标签和星期几标签,以便我知道哪个属于哪个。

现在我试图在for循环中尝试这样做,但遇到了分组部分的问题。

同样,我们的目标是进行滚动平均预测,但是根据每个出口的星期和月份(忘了包含那些。有多个出口和月份)

任何帮助都会很棒!!

1 个答案:

答案 0 :(得分:0)

roll如果没有5,则计算5或更少的滚动均值。ave将其应用于每个组。

library(zoo)

roll <- function(x) rollapplyr(x, 5, mean, partial = TRUE)
transform(DF, ma = ave(visitors, Outlet, weekday, Month, FUN = roll))

结果将ma列添加到输入:

         Outlet weekday visitors Month   ma
1  jackInthebox  Monday       10  July 10.0
2  jackInthebox  Monday       11  July 10.5
3  jackInthebox    Tues       15  July 15.0
4  jackInthebox    Tues       16  July 15.5
5  jackInthebox     Wed       30  July 30.0
6  jackInthebox     Wed       28  July 29.0
7           KFC  Monday       50  July 50.0
8           KFC  Monday       53  July 51.5
9           KFC    Tues       60  July 60.0
10          KFC    Tues       64  July 62.0
11          KFC     Wed       30  July 30.0
12          KFC     Wed       31  July 30.5

注意:这是假定的输入DF

Lines <- "
Outlet        weekday    visitors   Month
jackInthebox    Monday  10          July      
jackInthebox    Monday  11          July       
jackInthebox    Tues    15          July
jackInthebox    Tues    16          July 
jackInthebox    Wed     30          July
jackInthebox    Wed     28          July 
KFC             Monday  50          July 
KFC             Monday  53          July 
KFC             Tues    60          July 
KFC             Tues    64          July
KFC             Wed     30          July
KFC             Wed     31          July"

DF <- read.table(text = Lines, header = TRUE, as.is = TRUE)