沿阵列中的n个维度之一选择

kai*_*kai 13 r multidimensional-array

我在R中有一个数组,由这样的函数创建:

A <- array(data=NA, dim=c(2,4,4), dimnames=list(c("x","y"),NULL,NULL))
Run Code Online (Sandbox Code Playgroud)

我想沿着一个维度选择,所以对于上面的例子,我会:

A["x",,]
dim(A["x",,])    #[1] 4 4
Run Code Online (Sandbox Code Playgroud)

有没有办法概括,如果我事先不知道我的数组可能有多少维度(除了我要选择的命名的维度)?我想编写一个函数来获取可能格式化为A的输入,或者:

B <- c(1,2)
names(B) <- c("x", "y")

C <- matrix(1, 2, 2, dimnames=list(c("x","y"),NULL))
Run Code Online (Sandbox Code Playgroud)

背景

一般背景是我正在研究ODE模型,因此对于deSolve的ODE函数,它必须采用具有当前状态的单个命名向量.对于其他一些函数,比如计算相位平面/方向场,使用更高维数组来应用微分方程更为实际,我希望避免使用相同函数的多个副本,只需使用不同的函数我想要选择的维度之后的逗号数量.

had*_*ley 10

我花了很多时间找出为plyr做这个的最快方法,我能想到的最好的方法是手动构建调用[:

index_array <- function(x, dim, value, drop = FALSE) { 
  # Create list representing arguments supplied to [
  # bquote() creates an object corresponding to a missing argument
  indices <- rep(list(bquote()), length(dim(x)))
  indices[[dim]] <- value

  # Generate the call to [
  call <- as.call(c(
    list(as.name("["), quote(x)),
    indices,
    list(drop = drop)))
  # Print it, just to make it easier to see what's going on
  print(call)

  # Finally, evaluate it
  eval(call)
}
Run Code Online (Sandbox Code Playgroud)

(您可以在https://github.com/hadley/devtools/wiki/Computing-on-the-language上找到有关此技术的更多信息)

然后您可以按如下方式使用它:

A <- array(data=NA, dim=c(2,4,4), dimnames=list(c("x","y"),NULL,NULL))
index_array(A, 2, 2)
index_array(A, 2, 2, drop = TRUE)
index_array(A, 3, 2, drop = TRUE)
Run Code Online (Sandbox Code Playgroud)

如果要基于多个维度进行提取,它也会以直接的方式进行推广,但您需要重新考虑函数的参数.


flo*_*del 5

我写了这个通用函数。不一定非常快,但是是arrayInd矩阵索引的一个很好的应用:

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

}
Run Code Online (Sandbox Code Playgroud)

例子:

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")
Run Code Online (Sandbox Code Playgroud)