如何沿第三维滚动阵列?

时间:2015-03-03 22:09:41

标签: r zoo

说我有阵列:

> arr <- array(1, dim=c(3, 3, 3))
, , 1

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    1    1    1

, , 2

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    1    1    1

, , 3

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    1    1    1

我想使用大小为2的滚动窗口来计算移动平均线。这意味着我想计算数组的每个第3维的移动平均值,将它们乘以2乘以2.最后,我会得到一些东西像:

> rollmeanThatWorksWithArrays(arr, k=2, margin=c(1, 2))
, , 1

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    1    1    1

, , 2

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    1    1    1

我可以使用apply(arr, margin=c(1, 2), mean)在第3维度上做这个意思,但是还没弄明白如何进行滚动操作。也许rollmean / rollapply根本不支持它,我将不得不编写自己的函数?

2 个答案:

答案 0 :(得分:1)

非常手动,你可以这样做(使用不同于你的阵列):

library(zoo)
arr <- array(1:27, dim=c(3, 3, 3))
res <- do.call(rbind ,tapply(c(arr), rep(1:9, 3), function(x) rollmean(x, k = 2)))
array(c(res), dim = c(3, 3, 2))
, , 1

     [,1] [,2] [,3]
[1,]  5.5  8.5 11.5
[2,]  6.5  9.5 12.5
[3,]  7.5 10.5 13.5

, , 2

     [,1] [,2] [,3]
[1,] 14.5 17.5 20.5
[2,] 15.5 18.5 21.5
[3,] 16.5 19.5 22.5

答案 1 :(得分:1)

假设输入arr与@ RStudent的答案一样。首先创建一个data.frame ix数组索引,这些索引定义arr的子集,然后取平均值。定义Mean以获取数组列表的均值。最后,对于每个ixk表单arr[,,k],将其转换为适合作为Mean输入的列表。取Mean并将结果简化为数组。

library(zoo)

w <- 2 # width

arr <- array(1:27, c(3, 3, 3))
n <- dim(arr)[3]

ix <- as.data.frame(t(rollapply(1:n, w, c)))
Mean <- function(L) Reduce("+", L) / length(L)
simplify2array(lapply(ix, function(ix) Mean(lapply(ix, function(k) arr[,,k]))))

,并提供:

, , V1

     [,1] [,2] [,3]
[1,]  5.5  8.5 11.5
[2,]  6.5  9.5 12.5
[3,]  7.5 10.5 13.5

, , V2

     [,1] [,2] [,3]
[1,] 14.5 17.5 20.5
[2,] 15.5 18.5 21.5
[3,] 16.5 19.5 22.5