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

4

2 回答 2

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)
于 2012-11-28T21:10:00.207 回答
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
于 2012-11-28T21:13:35.483 回答