rollapply 二维数组 (R) [英] rollapply for two-dimensional arrays (R)
问题描述
我想做一些事情,我认为使用 rollapply
应该很容易实现,但我遇到了一些麻烦.
There is something I want to do which I believe should be easily achieved with rollapply
, but I am having some trouble.
对于简单的向量,我们有
For simple vectors we have
> a <- c(1:10)
> a
[1] 1 2 3 4 5 6 7 8 9 10
> rollapply(a, 2, mean)
[1] 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5
这是应该的.但是对于更高的维度会出现问题
which is as it should be. But problems arise for higher dimensions
> b <- array(c(1:6), c(2,3))
> b
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
> rollapply(b, 2, mean)
[,1] [,2] [,3]
[1,] 1.5 3.5 5.5
如果我想要应用于列,这很好 - 但肯定也必须有某种方法可以应用于行并获得
which is fine if I want to apply over columns - but surely there must also be some way to apply over rows instead and get
[,1] [,2]
[1,] 2 4
[2,] 3 5
rollapply
函数无法做到这一点,我可以看到.
The rollapply
function offers no way to do this that I can see.
推荐答案
我们可以简单地使用 apply
和 MARGIN = 1
循环遍历行并应用 滚动应用代码>.
MARGIN
也可以针对更高的维度进行调整,即它是更通用的解决方案
We can simply use apply
with MARGIN = 1
to loop over the rows and apply the rollapply
. The MARGIN
can be adjusted for higher dimensions as well i.e. it is more general solution
t(apply(b, 1, function(x) rollapply(x, 2, mean)))
-输出
# [,1] [,2]
#[1,] 2 4
#[2,] 3 5
或使用 collapse
library(collapse)
dapply(b, FUN = function(x) rollapply(x, 2, fmean), MARGIN = 1)
这篇关于rollapply 二维数组 (R)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!