我试图了解align
参数在rollapply
中的作用。我已阅读了文档?rollapply
(对齐)中的描述:
指定结果的索引应为左还是左 与的滚动窗口相比右对齐或居中(默认) 观察。仅当width表示宽度时才使用此参数。
我不清楚这意味着什么,也没有示例。在这里提出了类似的问题:alignment and offsets in rollapply,但没有人解释。
希望有人可以通过一些示例对此进行更详细的说明。我尝试进行实验以尝试更好地理解它,但是当我尝试align =“ right”,“ left”或“ center”时,我不确定结果如何改变。
答案 0 :(得分:1)
这里是一个例子:
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
答案 1 :(得分:1)
右对齐。在下面的计算中,结果为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
等效的方法是通过偏移量。那就是将前一个,当前和下一个值馈入求和:
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