我有特定周内促销产品的数据集,我想计算过去4个非促销周(用标志表示)从促销到非促销期间产品的平均销售额。如果交易是在非促销期内进行的,我们应该照原样进行销售。我们必须计算最近非促销周的平均销售额,它们可能是非连续的。
请注意
structure(list(Product_group = structure(c(1L, 1L, 1L, 1L, 1L,
1L), .Label = "A", class = "factor"), Promo = structure(c(1L,
1L, 2L, 1L, 1L, 2L), .Label = c("0", "1"), class = "factor"),
Week = structure(c(1L, 2L, 2L, 3L, 4L, 5L), .Label = c("2017-01-01",
"2017-01-02", "2017-01-04", "2017-01-05", "2017-01-06", "2017-01-08",
"2017-01-09"), class = "factor"), Sales = c(50, 50, 60, 70,
50, 50)), .Names = c("Product_group", "Promo", "Week", "Sales"
), row.names = c(NA, 6L), class = "data.frame")
head(df)
Product_group Promo Week Sales
1 A 0 2017-01-01 50
2 A 0 2017-01-02 50
3 A 1 2017-01-02 60
4 A 0 2017-01-04 70
5 A 0 2017-01-05 50
6 A 1 2017-01-06 50
我正在寻找这样的输出
Product_group Promo Week Sales Avg Pre Promo Sales
1 A 0 2017-01-01 50 50 # Since it is non promo
2 A 0 2017-01-02 50 50
3 A 1 2017-01-02 60 50 # 100/2
4 A 0 2017-01-04 70 70
5 A 0 2017-01-05 50 50
6 A 1 2017-01-06 50 55 # (50 +70 + 50 + 50 )/4