具有 moving/rolling 平均值的函数的循环?

For loop with a function for a moving/rolling average?

本质上(在 R 中),我想在一段时间内应用移动平均函数(例如日期和时间变量)以查看特定指标如何随时间变化。但是,度量本身是一个函数。分数可以是 1(赞成)、0(中立)或 -1(否定)。指标的函数是:

function(pro, neg, total) {
x <- (pro / total) * 100
y <- (neg / total) * 100
x - y
}

所以1的百分比减去-1的百分比就是度量值。

给定每个记录分数的时间戳,我想将该指标评估为所有行的移动平均值。我认为 for 循环 是应用此方法的最佳方法,但我对如何执行此操作感到困惑。

有没有人有什么想法/建议?

如评论中所述,zoo 中的 rollapply() 是一个不错的选择。我冒昧地生成了一些示例数据,如果它与您的不相似,我们深表歉意。

library(zoo)

f <- function(x, l) {
    p <- sum(x == 1) / l
    n <- sum(x == -1) / l
    (p - n)*100
}

# Or more efficiently
f <- function(x, l=length(x)) {
    (sum(x)/l)*100
}

set.seed(1)
N <- 25
dtf <- data.frame(time=as.Date(15000+(1:N)), score=sample(-1:1, N, rep=TRUE))

score <- read.zoo(dtf)
l <- 8
zts <- cbind(score, rolling=rollapply(score, l, f, l, fill=NA))

zts
#            score rolling
# 2011-01-27    -1      NA
# 2011-01-28     0      NA
# 2011-01-29     0      NA
# 2011-01-30     1    12.5
# 2011-01-31    -1    25.0
# 2011-02-01     1    12.5
# 2011-02-02     1     0.0
# 2011-02-03     0   -25.0
# 2011-02-04     0     0.0
# 2011-02-05    -1   -12.5
# 2011-02-06    -1   -12.5
# 2011-02-07    -1   -12.5
# 2011-02-08     1     0.0
# 2011-02-09     0    25.0
# 2011-02-10     1    37.5
# 2011-02-11     0    62.5
# 2011-02-12     1    62.5
# 2011-02-13     1    50.0
# 2011-02-14     0    37.5
# 2011-02-15     1    25.0
# 2011-02-16     1     0.0
# 2011-02-17    -1      NA
# 2011-02-18     0      NA
# 2011-02-19    -1      NA
# 2011-02-20    -1      NA