首页 > 解决方案 > Performing a rolling average with criteria in R

问题描述

Been trying to learn the most basic of items at first and then expanding the complexity. So for this one, how would I modify the last line to where it would be create a rolling 12 month average for each seriescode. In this case, it would produce an average of 8 for seriescode 100 and 27 for seriescode 101.

First, is the sample data

Monthx<- c(201911,201912,20201
         ,20202,20203,20204,20205,20206,20207
         ,20208,20209,202010,202011,201911,201912,20201
         ,20202,20203,20204,20205,20206,20207
         ,20208,20209,202010,202011)

empx <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,21,22,23,24,25,26,27,28,29,20,31,32,33)

seriescode<-c(100,100,100,100,100,100,100,100,100,100,100,100,100,110,110,110,110,110,110,110,110,110,110,110,110,110)

ces12x <- data.frame(Monthx,empx,seriescode)

Manipulations

library(dplyr)

ces12x<- ces12x %>% mutate(year = substr(as.numeric(Monthx),1,4),
                           month = substr(as.numeric(Monthx),5,7),
                           date = as.Date(paste(year,month,"1",sep ="-")))
                           Month_ord <- order(Monthx)

ces12x<-ces12x %>% mutate(ravg = zoo::rollmeanr(empx, 12, fill = NA))

标签: raveragerolling-average

解决方案


If you want to continue using the tidyverse for this, the following should do the trick:

library(dplyr)

ces12x %>%
  group_by(seriescode) %>%
  arrange(date) %>%
  slice(tail(row_number(), 12)) %>%
  summarize(ravg = mean(empx))

推荐阅读