arrays - 使用索引向量对数组进行子集
问题描述
如何使用索引向量对数组进行子集化?这可能更容易通过一个例子来说明。
# 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)))
解决方案
一种方法,虽然它看起来并不那么漂亮。
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`[<-`(bn, TRUE, "a", "b")
。 知道要动态生成参数列表,我立刻想到了
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
是您的轴,在您认为必要时确定它们。
推荐阅读
- node.js - 在服务器中发送请求后如何检查状态?
- php - 使用 PHP LibreOffice 和 ncjoes/office-converter 库转换文件
- mysql - 检测第一个查询是否在sql中完成然后运行第二个
- java - Spring boot api通过上传excel表计算批量学生cgpa
- python - Selenium 中的刮擦表和长单行打印而不是列和行
- php - 高级自定义字段插件用户下拉菜单不起作用
- node.js - 如何在 GraphQL 中对嵌套数据进行分组
- database - 如何将数据库表和列翻译成另一种语言?
- python - python pandas 为我分组的列提供了一个关键错误,即使布尔表达式显示该列是数据框的一部分
- html - 为什么子 div 继承父母的身高 100%?