r - R 中的居中移动平均线(不使用包)

标签 r moving-average

我一直在 R 中构建一个中心移动平均函数(没有使用任何包),并且遇到了如下挑战:

如您所知,居中移动平均线包括合并“不完整部分”(即数据点的开头和结尾)的概念。例如,考虑下面的向量 p:

p <- c(10,20,30,40,50,60,70,80,90)

在这种情况下,我感兴趣的中心移动平均线如下所示:

x <- ((10+20)/2, (10+20+30)/3, (20+30+40)/3 ..... (70+80+90)/3, (80+90)/2)

为了实现上述目标,我尝试使用 if 函数,如下所示:

wd 表示窗口大小

mov_avg <- function(p, wd) {
  x <- c(0, cumsum(p))
  if ((p > p[1])&(p < p[length(p)])) {
    neut <- 1:(length(p)-(wd-1))
    upper <- neut+(wd-1)
    x <- (x[upper]-x[neut])/(upper-neut)
  } else if (p==p[1]) {
    neut <- 0
    upper <- neut+3
    x <- (x[upper]-x[neut])/(upper-1-neut)
  } else if (p==p[length(p)]) {
    upper <-(length(p)+1)
    neut <- (length(p)-(wd-2))
    x <- (x[upper]-x[neut])/(upper-neut)
  }
  return(x)
}

然后我输入下面一行来执行:

mov_avg(p, 3)

我遇到如下错误:

numeric(0)
Warning messages:
1: In if ((p > p[1]) & (p < p[length(p)])) { :
  the condition has length > 1 and only the first element will be used
2: In if (p == p[1]) { :
  the condition has length > 1 and only the first element will be used

有人可以帮助我使这个功能有效吗?

谢谢!

最佳答案

在 base R 中做这样的事情怎么样:

window <- 3
p <- c(10,20,30,40,50,60,70,80,90)

x <- c(NA, p, NA)
sapply(seq_along(x[-(1:(window - 1))]), function(i)
    mean(x[seq(i, i + window - 1)], na.rm = T))
#[1] 15 20 30 40 50 60 70 80 85

诀窍是添加侧翼 NA,然后使用 meanna.rm = T


我知道你说“不使用包”,但使用 zoo::rollapply

时更短
library(zoo)
rollapply(c(NA, p, NA), 3, mean, na.rm = T)
#[1] 15 20 30 40 50 60 70 80 85

关于r - R 中的居中移动平均线(不使用包),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51471720/

相关文章:

从 geom_tile 中删除空行

r - 无法在 R 中编译 RcppArmadillo

r - R中范围数据的移动平均值

matlab - 我如何(有效地)计算向量的移动平均值?

python - Pandas 移动平均线 - 下降负值?

r - 创建一个列,列出该特定行中包含负值的所有列名称

r - 使用离散化时无法在 mgcv 中生成预测(离散=T)

R - 返回默认值的函数 - getOrElse

r - 将移动平均图添加到R中的时间序列图

algorithm - "Time Aware"指数移动平均线