简体   繁体   English

创建一个循环来计算不同滚动平均值长度的矢量的滚动平均值

[英]Creating a loop that calculates the rolling mean of a vector for different rolling mean lengths

I am trying to create a "for loop" setup that is going calculate different rolling means of a return series, where I use rolling means ranging from the last 2 observations to the last 16 observations. 我正在尝试创建一个“ for循环”设置,该设置将计算返回系列的不同滚动方式,其中使用的滚动方式范围从最后2个观察值到最后16个观察值。 kϵ[2,16]. Kε[2,16]。 I've been trying to use a function like this, where the "rollmean" is a function from zoo. 我一直在尝试使用这样的函数,其中“ rollmean”是来自Zoo的函数。 This produces the warning "Warning message: In roll[i] <- rollmean(x, i) : number of items to replace is not a multiple of replacement length" Can someone please help me? 这将产生警告“警告消息:在roll [i] <-rollmean(x,i)中:要替换的项目数不是替换长度的倍数”有人可以帮助我吗?

rollk <- function(x, kfrom= 2, kto=16){
roll <- as.list(kto-kfrom+1)
for (i in kfrom:kto){
roll[i]<- rollmean(x, i)
return(roll)
}}

I suppose you want 我想你要

# library(zoo)
rollk <- function(x, kfrom = 2, kto = 16){
  roll <- list()
  ft <- kfrom:kto
  for (i in seq_along(ft)){
    roll[[i]]<- rollmean(x, ft[i])   
  }
  return(roll)
}

There are several problems in your function: 您的函数中存在几个问题:

  • You need [[ to access a single list element, not [ . 您需要[[访问单个列表元素,而不需要[
  • You want a list of length length(krom:kto) . 您需要一个长度为length(krom:kto)的列表。 Now, i starts at 1 , not at kfrom . 现在, i1开始,而不是从kfrom
  • Now, roll is returned after the for loop. 现在,在for循环之后返回roll Hence, the function returns a single list containing all values. 因此,该函数返回包含所有值的单个列表。

A shorter equivalent of the function above: 上面的函数的较短等效项:

rollk2 <- function(x, kfrom = 2, kto = 16)
  lapply(seq(kfrom, kto), function(i) na.omit(filter(x, 1 / rep(i, i))))

It does not require loading additional packages. 它不需要加载其他软件包。

Try this: 尝试这个:

library(zoo)
lapply(2:16, rollmean, x = x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM