2014-06-05 76 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

相關問題