数组索引保留结构

时间:2012-11-28 20:27:47

标签: r multidimensional-array

我需要一个在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之外的某个值开始。我还需要保留数组结构,因此矩阵索引到数组中看起来并不吸引人。提前谢谢。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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