首页 > 解决方案 > 使用索引向量对数组进行子集

问题描述

如何使用索引向量对数组进行子集化?这可能更容易通过一个例子来说明。

# I have this array
bn <- structure(c(0.8, 0.09, 0.11, 0.09, 0.8, 0.11, 0.11, 0.11, 0.78, 
0.18, 0.13, 0.69, 0.88, 0.07, 0.05, 0.25, 0.49, 0.26, 0.43, 0.2, 
0.37, 0.34, 0.39, 0.27, 0.13, 0.44, 0.42), class = "table", .Dim = c(3L, 
3L, 3L), .Dimnames = structure(list(D = c("a", "b", "c"), A = c("a", 
"b", "c"), C = c("a", "b", "c")), .Names = c("D", "A", "C")))    

# and matrix of indices (correspond to dimensions of bn)
input <- structure(c("a", "b", NA), .Dim = c(1L, 3L), 
                   .Dimnames = list(NULL, c("A", "C", "D")))

我可以bn通过直接索引子集来给出结果

bn[, input[,"A"], input[,"C"]]
#    a    b    c 
# 0.18 0.13 0.69 

我怎样才能做到这一点而不像这样分解它(虽然我事先不知道数组的维度,但它将是输入的数量 + 1)。基于r-subset-array-using-vector(尽管该问题是针对列表而不是数组),我尝试了

bn[, input[,c("A","C")]]
bn[, input[,c("A","C"), drop=FALSE]]

[.default(bn, input[, c("A", "C"), drop = FALSE], )
中给出错误:维数不正确

这可行,但会花费太多时间来强制和构建索引。

library(R.utils)
x = array(bn, dim=dim(bn), dimnames=dimnames(bn))
extract(x, indices=list("2"=1, "3"=2))

我也可以melt数据然后拉出相关行,还有这个问题subset-an-array-for-the-pairs-of-indices-in-r ] 但解决方案预设了数组的维度。

有没有一种简洁的方法可以通过子集来做到这一点array


另一种选择:

library(gRbase)
inp = input[,c("A", "C"), drop=FALSE]
ar_slice(bn, split(inp, colnames(inp)))

但是如果没有工作就好了split

或从 r2evans 带头

ar_slice(bn, setNames(as.list(inp), colnames(inp)))

标签: arraysrsubset

解决方案


一种方法,虽然它看起来并不那么漂亮。

do.call(`[`, c(list(bn), list(TRUE), as.list(input[,c("A","C")])))
#    a    b    c 
# 0.18 0.13 0.69 

我会追踪我是如何想到的。

  1. 最初,我们只想要bn[,"a","b"]. 意识到这与db[TRUE,"a","b"].
  2. 将 转换[为函数 ala `[<-`(bn, TRUE, "a", "b")
  3. 知道要动态生成参数列表,我立刻想到了do.call,所以我们需要知道如何以(bn, TRUE, "a", "b")编程方式创建。最后一部分是:

    as.list(input[,c("A","C")])
    # $A
    # [1] "a"
    # $C
    # [1] "b"
    

    所以我们可以通过添加list-ifiedbn和来创建所有参数TRUE

    str( c(list(bn), list(TRUE), as.list(input[,c("A","C")])) )
    # List of 4
    #  $  : 'table' num [1:3, 1:3, 1:3] 0.8 0.09 0.11 0.09 0.8 0.11 0.11 0.11 0.78 0.18 ...
    #   ..- attr(*, "dimnames")=List of 3
    #   .. ..$ D: chr [1:3] "a" "b" "c"
    #   .. ..$ A: chr [1:3] "a" "b" "c"
    #   .. ..$ C: chr [1:3] "a" "b" "c"
    #  $  : logi TRUE
    #  $ A: chr "a"
    #  $ C: chr "b"
    

这是假设您的第一个轴始终是“满的”(TRUE)。如果您需要动态确定,只需知道列表中的第二个及其他元素do.call是您的轴,在您认为必要时确定它们。


推荐阅读