Select along one of n dimensions in array

后端 未结 4 1330
青春惊慌失措
青春惊慌失措 2020-12-05 19:53

I have an array in R, created by a function like this:

A <- array(data=NA, dim=c(2,4,4), dimnames=list(c(\"x\",\"y\"),NULL,NULL))

And I

4条回答
  •  感动是毒
    2020-12-05 20:20

    Perhaps there is an easier way, but this works:

    do.call("[",c(list(A,"x"),lapply(dim(A)[-1],seq)))
         [,1] [,2] [,3] [,4]
    [1,]   NA   NA   NA   NA
    [2,]   NA   NA   NA   NA
    [3,]   NA   NA   NA   NA
    [4,]   NA   NA   NA   NA
    

    Let's generalize it into a function that can extract from any dimension, not necessarily the first one:

    extract <- function(A, .dim, .value) {
        idx.list <- lapply(dim(A), seq_len)
        idx.list[[.dim]] <- .value
        do.call(`[`, c(list(A), idx.list))
    }
    

    Example:

    A <- array(data=1:32, dim=c(2,4,4),
               dimnames=list(c("x","y"), LETTERS[1:4], letters[1:4]))
    
    extract(A, 1, "x")
    extract(A, 2, "D")
    extract(A, 3, "b")
    

提交回复
热议问题