2012-11-28 94 views
5

我需要一個函數,它將R中的多維數組進行子集化;抓住是我不知道直到函數被調用之前沿該維度的哪個維度或長度。數組索引保持結構

# subset a 3-d array; leave dims 1 and 2, but start 3rd dim at its 11th value 
mydim <- dim(myarr) 
myarr[, , 11:mydim[3]] 

# subset a 4-d array; leave dims 1, 3 and 4, but start 2rd dim at its 8th value 
mydim <- dim(myarr) 
myarr[, 8:mydim[2], , ] 

我總是需要精確地沿着一個維度子集,該子集總是比1。我還需要保持陣列結構的其他一些值來啓動,所以矩陣索引到數組看起來並不吸引人。提前致謝。

+0

有趣。當你說「多少」時,你的意思是沿着這個維度有多少長度或不同的東西? –

+0

是的,我的意思是沿着那個維度的長度 –

+0

我woukld建議這種操作列表() –

回答

1

下面是需要創建子集基於矩陣陣列的可能性優勢的選項:

myarr <- array(1:(2*3*4), dim = c(2, 3, 4)) 

myfun <- function(arr, from, len, Dim){ 
    dimArr <- dim(arr) 
    if(missing(len)){ 
     subIdx <- from:dimArr[Dim] 
    } else { 
     subIdx <- from:(from + len - 1) 
    } 
    arrD <- lapply(as.list(dimArr), seq_len) 
    arrD[[Dim]] <- subIdx 
    subMat <- as.matrix(do.call(expand.grid, arrD)) 
    array(arr[subMat], dim = lapply(arrD, length)) 
} 

> myfun(myarr, 2, 1, 3) 
, , 1 

    [,1] [,2] [,3] 
[1,] 7 9 11 
[2,] 8 10 12 

> myfun(myarr, 2, Dim = 3) 
, , 1 

    [,1] [,2] [,3] 
[1,] 7 9 11 
[2,] 8 10 12 

, , 2 

    [,1] [,2] [,3] 
[1,] 13 15 17 
[2,] 14 16 18 

, , 3 

    [,1] [,2] [,3] 
[1,] 19 21 23 
[2,] 20 22 24 
+0

@JackTanner剛剛看到(並且以不同的方式理解)「長度一致」評論。如果編輯沒有做你想要的,請告知! – BenBarnes

1

這裏我們開始吧!測試的太...

sampleArray <- function(myarr, dm, start, leng) { 
    ## arguments: 
    ## dm is the dimension selected 
    ## start is where in dm to being 
    ## leng is how far in from dm to go 
    ## start+leng <= dim(myarr)[dm] 

    leng <- leng-1 

    # error check 
    if (start+leng > dim(myarr)[dm]) 
     warning("leng too long by ", start+leng - dim(myarr)[dm], ".") 

    #initialize a vector of all TRUE 
    indx <- as.list(rep(TRUE, length(dim(myarr)))) 

    # change the required dimension to the required sequence 
    indx[[dm]] <- seq(start, start+leng) 
    indx <- paste(indx, collapse=",") 

    expr <- paste0("myarr[", indx, "]") 

    # return the appropriate sample 
    eval(parse(text=expr)) 
    } 

例如:

# sample array 
myarr <- array(1:2250, dim=c(15, 10, 15)) 

# example call 
sampleArray(myarr, dm=2, start=4, leng=3) 
+0

不起作用:indx是一個向量,並且將其第三個值更改爲另一個向量失敗,「要替換的項數不是替換長度的倍數「 –

+0

@Jack坦納 - 剛編輯它。它現在應該工作 –

+0

它幾乎可行!你的意思是start + leng-1。我接受了另一個答案,因爲它沒有bug,但是感謝給我一個很好的選擇。 –