Arrays 使用索引向量对数组进行子集划分
如何使用索引向量对数组进行子集划分? 这可能更容易通过一个例子来说明Arrays 使用索引向量对数组进行子集划分,arrays,r,subset,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 = "tab
# 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")))
我如何做到这一点而不进行这样的分解(虽然我不知道数组的维数,但它将是输入数+1)。基于(尽管这个问题是针对列表而不是数组),我尝试了
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))
我还可以融化
数据,然后拉出相关行,然后
还有一个问题]
但解决方案以阵列的尺寸为前提
有没有一种简洁的方法可以通过将数组子集化来实现这一点
另一种选择是:
library(gRbase)
inp = input[,c("A", "C"), drop=FALSE]
ar_slice(bn, split(inp, colnames(inp)))
但是如果没有split
或者从埃文斯身上领头
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
我会追查我是怎么想到的
最初,我们只需要bn[,“a”,“b”]
。认识到这与db[TRUE,“a”,“b”]
相同
将[
转换为函数,ala`[谢谢..看起来这就是ar\u slice
(或者实际上是gRbase::tabSlice2
)在引擎盖下所做的事情。
do.call(`[`, c(list(bn), list(TRUE), as.list(input[,c("A","C")])))
# a b c
# 0.18 0.13 0.69
as.list(input[,c("A","C")])
# $A
# [1] "a"
# $C
# [1] "b"
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"