使用索引向量对数组进行子集

时间:2018-10-26 17:52:31

标签: arrays r subset

如何使用索引向量对数组进行子集设置? 通过示例可能更容易显示。

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

1 个答案:

答案 0 :(得分:2)

一种方法,尽管看起来并不那么漂亮。

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. [转换为函数`[<-`(bn, TRUE, "a", "b")
  3. 知道要动态生成参数列表,我立即想到了do.call,因此我们需要知道如何以编程方式创建(bn, TRUE, "a", "b")。最后一部分是:

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

    因此,我们可以在list开头的bnTRUE前面添加一系列参数:

    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中列表的第二个元素是您的轴,请根据需要确定它们。

相关问题