2014-06-05 30 views
2

我有一个3维的数组。我想将一个函数应用到第三维并返回一个数组。我非常高兴plyr :: aaply几乎可以做到我想要的。然而,它围绕我的数组的维度交换。文件告诉我这是幂等的,(在我查阅之后)让我认为结构应该保持不变。这是身份函数的一个可重复的例子。我可以修改它以保留数组维度的顺序吗?如何使用aaply并保持数组中的维度顺序?

nRow <- 10 
nCol <- 10 
nAge <- 7 

#creating the array 
dimnames <- list(NULL,NULL,NULL) 
names(dimnames) <- c("x","y","age") 
aF <- array(0, dim=c(nCol,nRow,nAge), dimnames=dimnames) 

#aaply the identity function to the 3rd dimension 
aTst <- aaply(aF, .margins=3, identity) 

dim(aF) 
#[1] 10 10 7 
dim(aTst) 
#[1] 7 10 10 

查看尺寸已从10,10,7改为7,10,10。我知道它可以使用aperm改回来,但是如果我能避免它会是好的。

aTst2 <- aperm(aTst, c(2, 3, 1)) 

这里有一些关于我实际试图用这个做的更多细节(谢谢@Simon O'Hanlon)。 y表示二维空间,并且在网格上的每个单元格上都有一个向量。我想移动各年龄组,使用此功能:

rtMove1 <- function(m, pMove=0.4) { 

    #create matrices of the 4 neighbour cells to each cell 
    mW = cbind(rep(0,nrow(m)), m[,-nrow(m)]) 
    mN = rbind(rep(0,ncol(m)), m[-ncol(m),]) 
    mE = cbind(m[,-1], rep(0,nrow(m))) 
    mS = rbind(m[-1,], rep(0,ncol(m))) 

    mArrivers <- pMove*(mN + mE + mS + mW)/4 
    mStayers <- (1-pMove)*m 

    mNew <- mArrivers + mStayers 
    return(mNew) 
} 

要启动popn,将所有年龄段中的所有细胞,我可以做到这一点。

#initiate 100 individuals of age 3 at 5,5 
aF[5,5,3] <- 100 

aTst <- aaply(aF, .margins=3, rtMove1) 

aTst[3,,] 

这个作品在重新分配popn:

 1 2 3 4 5 6 7 8 9 10 
    1 0 0 0 0 0 0 0 0 0 0 
    2 0 0 0 0 0 0 0 0 0 0 
    3 0 0 0 0 0 0 0 0 0 0 
    4 0 0 0 0 10 0 0 0 0 0 
    5 0 0 0 10 60 10 0 0 0 0 
    6 0 0 0 0 10 0 0 0 0 0 
    7 0 0 0 0 0 0 0 0 0 0 
    8 0 0 0 0 0 0 0 0 0 0 
    9 0 0 0 0 0 0 0 0 0 0 
    10 0 0 0 0 0 0 0 0 0 0 

但我需要使用aperm重新排列的尺寸,如果我不想重复。

感谢, 安迪

+0

幂等的意味着它仍然与subseqent调用相同:IE F^N(x)= F (X)。 – James

+0

你真的想要应用什么功能?你知道'base :: apply'函数可以在任意数量的数组上运行吗? (aF,1:3,身份)'或'apply(aF,3,sum)'给出了第三维中每个2D矩阵的总和(在这种情况下是7'0的矢量)。 –

回答

-1

你可以尝试

aTst <- aaply(aF, c(1,2,3), identity) 

这应该做的伎俩

+0

这将返回列表... @Andy - 他需要返回数组,他清楚地提到。 – vrajs5

相关问题