R中不同组的度量的总和

时间:2018-04-26 11:27:47

标签: r

我有不同城市的月度销售数据,我想在3个月的基础上进行累计。

Month, City, Sales
Jan, Paris, 1000
Jan, NY , 2000
feb, Paris , 1200
Feb, NY, 3000
Mar, Paris, 1000
Mar, NY, 2000
April, Paris, 1400
April, NY, 1000
May, Paris, 2000
May, NY, 1000

现在,我想将过去3个月的总和作为每月和每个城市的输出,如下所示。

Month, City, Sales,  R3Month
Jan, Paris, 1000 , 1000
Jan, NY , 2000 , 2000
feb, Paris , 1300 , 2300
Feb, NY, 3000 , 5000
Mar, Paris, 1000 , 3300
Mar, NY, 2000 , 7000
April, Paris, 1400, 3700
April, NY, 1000 , 6000
May, Paris, 2000, 4400
May, NY, 1000 , 4000

任何线索都会受到高度赞赏。

由于

1 个答案:

答案 0 :(得分:2)

使用ave按城市和rollapplyr进行分组以执行实际滚动总和。 partial=TRUE导致它在每个城市的前两个月使用部分金额。

library(zoo)

roll <- function(x) rollapplyr(x, 3, sum, partial = TRUE)
transform(DF, R3Month = ave(Sales, City, FUN = roll))

,并提供:

   Month  City Sales R3Month
1    Jan Paris  1000    1000
2    Jan    NY  2000    2000
3    feb Paris  1300    2300
4    Feb    NY  3000    5000
5    Mar Paris  1000    3300
6    Mar    NY  2000    7000
7  April Paris  1400    3700
8  April    NY  1000    6000
9    May Paris  2000    4400
10   May    NY  1000    4000

注意

可重复输入的输入:

Lines <- "
Month, City, Sales
Jan, Paris, 1000
Jan, NY , 2000
feb, Paris , 1300
Feb, NY, 3000
Mar, Paris, 1000
Mar, NY, 2000
April, Paris, 1400
April, NY, 1000
May, Paris, 2000
May, NY, 1000"
DF <- read.csv(text = Lines, as.is = TRUE, strip.white = TRUE)