5

The diff function in R returns suitably lagged and iterated differences.

x = c(1, 2, 1, 3, 11, 7, 5)
diff(x)
# [1]  1 -1  2  8 -4 -2
diff(x, lag=2)
[1]  0  1 10  4 -6

Is there anyway to customize this so that we can use functions other than difference? For example, sum:

itersum(x)
# 3 3 4 14 18 12
4

3 回答 3

8

在基础 R 中,有filter函数。它不像友好和一般,zoo::rollapply但它非常快。在您的情况下,您希望应用带有权重的卷积过滤器c(1, 1)

itersum <- function(x, n = 2) tail(filter(x, rep(1, n)), sides = 1), -(n-1))

itersum(x)
# 3 3 4 14 18 12

为了给你更多的想法,这里是如何重写diff和函数:cumsumfilter

diff   <- function(x) head(filter(x, c(1, -1)), -1)
cumsum <- function(x) filter(x, 1, method = "recursive")

一般来说,如果您要滚动二进制函数,那么head并且tail可能是最简单和最快的方法,因为它将利用矢量化函数:

itersum     <- function(x) tail(x, -1) + head(x, -1)
diff        <- function(x) tail(x, -1) - head(x, -1)
sign.change <- function(x) tail(sign(x), -1) != head(sign(x), -1)
于 2013-07-28T14:50:59.480 回答
4

您可以使用zoo::rollapply

require(zoo)
x <- c(1, 2, 1, 3, 11, 7, 5)
rollapply(x, width = 2, FUN = sum)
## [1]  3  3  4 14 18 12
于 2013-07-28T14:33:22.783 回答
0

作为记录,我问这个问题是为了弄清楚如何在数字向量中注册符号变化,感谢@dickoa 的回答,我是这样完成的:

require(zoo)
equals = function(x) all(diff(x) == 0)
x = c(2, 3, -1, 3, -2, -5)
y = sign(x)
rollapply(y, 2, equals)
[1]  TRUE FALSE FALSE FALSE  TRUE
于 2013-07-28T14:50:36.573 回答