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

标签 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]]

which give Error in [.default(bn, input[, c("A", "C"), drop = FALSE], ) :
incorrect number of dimensions

这可行,但会花费太多时间在强制上 并构建索引。

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

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

是否有一种简洁的方法可以通过对数组进行子集化来实现此目的?


另一种选择:

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

最佳答案

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

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来创建全部参数。 -化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内列表的第二个及之后的元素即可。是你的轴,根据你的需要确定它们。

关于arrays - 使用索引向量对数组进行子集化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53013962/

相关文章:

c - 在 c 中将整数复制到 char * 时出现奇怪的结果

php - 将文件内容转换为 JavaScript 数组

r - 在 group_by 中使用列索引而不是名称

python - 从 panda DataFrame 创建 pd.Series 列表

r - R shiny 中的多个 react 性选择输入

c - 将整数分配给数组会导致垃圾

ruby - 从数组强制

r - {{}} 双大括号如何在 dplyr 中工作?

r - 由于不需要的因素而更改代码