我试图了解align
参数在rollapply
中的作用。我已阅读文档?rollapply
(align)中的描述:
指定与观察的滚动窗口相比,结果的索引是左对齐还是右对齐(默认)。仅当width表示宽度时才使用此参数。
我不清楚这意味着什么,没有例子。这里也提出了类似的问题:alignment and offsets in rollapply,但没人解释。
希望有人可以通过一些例子更详细地解释这一点。我尝试过尝试更好地理解它,但是当我尝试align =“right”,“left”或“center”时,我不确定我的结果是如何被改变的。
正确对齐。对于以下情况,它计算结果为y [i] = x [i-2] + x [i-1] + x [i]:
x <- 1:10
y <- rollapply(x, 3, sum, align = "right", fill = NA)
y
## [1] NA NA 6 9 12 15 18 21 24 27
计算如下:
rollapply(x, 3, function(x) paste(x, collapse = "+"), align = "right", fill = NA)
## [1] NA NA "1+2+3" "2+3+4" "3+4+5" "4+5+6" "5+6+7"
## [8] "6+7+8" "7+8+9" "8+9+10"
指定此的等效方式是根据偏移量。也就是说,将元素2的位置向后移动,向后移动1个位置,将当前位置移动到sum
:
rollapply(x, list(c(-2, -1, 0)), sum, fill = NA) # same as align = "right"
中心对齐。对于以下情况,它将结果计算为y [i] = x [i-1] + x [i] + x [i + 1]:
x <- 1:10
y <- rollapply(x, 3, sum, align = "center", fill = NA)
y
## [1] NA 6 9 12 15 18 21 24 27 NA
计算如下:
rollapply(x, 3, function(x) paste(x, collapse = "+"), align = "center", fill = NA)
## [1] NA "1+2+3" "2+3+4" "3+4+5" "4+5+6" "5+6+7" "6+7+8"
## [8] "7+8+9" "8+9+10" NA
指定此方法的等效方法是通过偏移量。这是将先前,当前和下一个值提供给sum:
rollapply(x, list(c(-1, 0, 1)), sum, fill = NA) # same as align = "center"
左对齐。对于以下内容,它将结果计算为y [i] = x [i] + x [i + 1] + x [i + 2]:
x <- 1:10
y <- rollapply(x, 3, sum, align = "left", fill = NA)
y
## [1] 6 9 12 15 18 21 24 27 NA NA
计算如下:
rollapply(x, 3, function(x) paste(x, collapse = "+"), align = "left", fill = NA)
## [1] "1+2+3" "2+3+4" "3+4+5" "4+5+6" "5+6+7" "6+7+8" "7+8+9"
## [8] "8+9+10" NA NA
这也可以根据偏移量来指定。这是使用当前,下一个和下一个后面的位置给sum
:
rollapply(x, list(c(0, 1, 2)), sum, fill = NA) # same as align = "left"
请注意,右对齐和中心对齐可以更紧凑地编写为:
y <- rollapplyr(x, 3, sum, fill = NA) # note r on the end to denote right
y <- rollapply(x, 3, sum, fill = NA) # no align specified so center
这是一个例子:
library(zoo)
rollapply(1:10, c(1, 2, 3), sum, align = "right")
#1
#2+1
#3+2+1
#4
#5+4
#6+5+4
#7
#8+7
#9+8+7
#10
rollapply(1:10, c(1, 2, 3), sum, align = "center")
#1
#2+3
#2+3+4
#4
#5+6
#5+6+7
#7
#8+9
#8+9+10
#10
rollapply(1:10, c(1, 2, 3), sum, align = "left")
#1
#2+3
#3+4+5
#4
#5+6
#6+7+8
#7
#8+9
#omitted because there are not enough values, see partial
#10
或者使用单个数字宽度更简单:
rollapply(1:10, 3, sum, align = "right", partial = TRUE)
#[1] 1 3 6 9 12 15 18 21 24 27
rollapply(1:10, 3, sum, align = "center", partial = TRUE)
#[1] 3 6 9 12 15 18 21 24 27 19
rollapply(1:10, 3, sum, align = "left", partial = TRUE)
#[1] 6 9 12 15 18 21 24 27 19 10