Select along one of n dimensions in array

后端 未结 4 1321
青春惊慌失措
青春惊慌失措 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:19

    I wrote this general function. Not necessarily super fast but a nice application for arrayInd and matrix indexing:

    extract <- function(A, .dim, .value) {
    
        val.idx  <- match(.value, dimnames(A)[[.dim]])
        all.idx  <- arrayInd(seq_along(A), dim(A))
        keep.idx <- all.idx[all.idx[, .dim] == val.idx, , drop = FALSE]
        array(A[keep.idx], dim = dim(A)[-.dim], dimnames = dimnames(A)[-.dim])
    
    }
    

    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")
    

提交回复
热议问题