我希望编写以下代码的sapply
版本。如您所见,for
代码将位置i
处的值替换为位置i-1
和i+1
处的平均值。如何使用sapply
执行此操作?
test <- c(1:length(x))
if(length(which(x > mean(x) + sd(x)*3)) > 0){
for (i in 1:length(x)) {
if(x[i] > mean(x) + sd(x)*3){
x[i] <- mean(x[i-1], x[i+1])
}
else{
x[i] <- x[i]
}
}
}
else{
test <- x
}
为了生成合适的(即非正常的)测试向量,我使用了rstable
包中的StableEstim
函数。
x <- rstable(100, alpha = 1.48, beta = 0.99, gamma = 0.27, delta = 3.36)
[不确定这是否对其他人有帮助,但是我找到了一种无需使用sapply
即可降低代码计算强度的方法:>
spiker <- function(x){ l <- c(which(x > mean(x) + sd(x)*3), which(x < mean(x) - sd(x)*3)) if(length(l) > 0){ for (i in l) { x[i] <- mean(x[i-1], x[i+1]) } x <- x spiker(x) } else{ x <<- x } }
唯一的问题是,如果向量
x
中的第一个或最后一个元素满足3 sd标准,则将不会计算平均值。