gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:16:11 24 4
gpt4 key购买 nike

我一直在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com