r - 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))
解决方案
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))
推荐阅读
- networking - OpenID Connect 提供程序 (IdentityServer4) 上有多个 URL?
- sql-server - Azure App 访问 Azure SQL Db IP 范围
- django - 在 Queryset 中使用 order_by 在 ArrayField 中找到 pks/ids 的顺序
- python - 如何为字典中的首字母创建多个字典?
- python - 我可以将 cookie 从 python 导出到 Chrome 吗?
- vue.js - 无法使用 Vuejs 从列表中删除选定的索引
- java - Spring Security 使用 PUT 方法返回 404
- python - 键盘一次中断多个线程
- node.js - 无法在 RHEL 上安装纱线
- r - 在 R 中使用 igraph 创建图形