如何计算R中的移动平均值
How to calculate a moving average in R
下面是示例数据。
Month<- c(20185,20186,20187,20189,201810,201811,201812,20191,20192,20193,20194,20195,20196,
20197,20198,20199,201910,201911,201912,20201
,20202,20203,20204,20205,20206,20207
,20208,20209,202010,202011)
emp<-c(2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,36,36,38,40,42,44,46,48,48,50,52,52,54,56)
第一个问题是我需要使用特定的函数,例如 roll_mean 还是我可以简单地使用平均值?
其次让它寻找最大日期(在本例中为 202011),然后构建过去 12 个月的平均值,以便将 202011 平均回溯到 201912,我将如何构建这样一个项目?
您可以使用任何滚动函数构建 12 个月的移动平均线。
library(dplyr)
df %>%
mutate(date = lubridate::ymd(paste0(ifelse(nchar(Month) == 5,
paste0(substring(Month, 1, 4), '0',
substring(Month, nchar(Month))), Month), '01'))) %>%
arrange(date) %>%
mutate(rolling_mean = zoo::rollmeanr(emp, 12, fill = NA))
如果您的数据已经排序,则无需构造 date
变量。你可以直接做:
df %>% mutate(rolling_mean = zoo::rollmeanr(emp, 12, fill = NA))
这是基本的 R 解决方案。
首先获取日期作为class
日期,然后存储月份的顺序,定义一个范围(span_month),最后遍历所有windows.
Month_t <- as.Date( paste0(
substr(Month,1,4),"-",substr(Month,5,length(Month)),"-1"),
"%Y-%m-%d" )
Month_ord <- order(Month_t)
span_month=12
sapply( 1:((length(Month_ord) + 1) - span_month),
function(x) mean(emp[Month_ord[x]:Month_ord[x + (span_month - 1)]]) )
# [1] 13.00000 15.00000 17.00000 19.00000 21.00000 23.16667 25.16667 27.16667
# [9] 29.16667 31.16667 33.16667 35.16667 37.16667 39.00000 40.83333 42.66667
#[17] 44.33333 45.83333 47.50000
下面是示例数据。
Month<- c(20185,20186,20187,20189,201810,201811,201812,20191,20192,20193,20194,20195,20196,
20197,20198,20199,201910,201911,201912,20201
,20202,20203,20204,20205,20206,20207
,20208,20209,202010,202011)
emp<-c(2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,36,36,38,40,42,44,46,48,48,50,52,52,54,56)
第一个问题是我需要使用特定的函数,例如 roll_mean 还是我可以简单地使用平均值? 其次让它寻找最大日期(在本例中为 202011),然后构建过去 12 个月的平均值,以便将 202011 平均回溯到 201912,我将如何构建这样一个项目?
您可以使用任何滚动函数构建 12 个月的移动平均线。
library(dplyr)
df %>%
mutate(date = lubridate::ymd(paste0(ifelse(nchar(Month) == 5,
paste0(substring(Month, 1, 4), '0',
substring(Month, nchar(Month))), Month), '01'))) %>%
arrange(date) %>%
mutate(rolling_mean = zoo::rollmeanr(emp, 12, fill = NA))
如果您的数据已经排序,则无需构造 date
变量。你可以直接做:
df %>% mutate(rolling_mean = zoo::rollmeanr(emp, 12, fill = NA))
这是基本的 R 解决方案。
首先获取日期作为class
日期,然后存储月份的顺序,定义一个范围(span_month),最后遍历所有windows.
Month_t <- as.Date( paste0(
substr(Month,1,4),"-",substr(Month,5,length(Month)),"-1"),
"%Y-%m-%d" )
Month_ord <- order(Month_t)
span_month=12
sapply( 1:((length(Month_ord) + 1) - span_month),
function(x) mean(emp[Month_ord[x]:Month_ord[x + (span_month - 1)]]) )
# [1] 13.00000 15.00000 17.00000 19.00000 21.00000 23.16667 25.16667 27.16667
# [9] 29.16667 31.16667 33.16667 35.16667 37.16667 39.00000 40.83333 42.66667
#[17] 44.33333 45.83333 47.50000