r - 按行名过滤矩阵的嵌套列表
问题描述
我有一个矩阵列表,该列表已被网络抓取。我希望按行名和列名过滤每个矩阵。我可以按行名和列表过滤矩阵,但不能按列表中的矩阵过滤!
一些数据
set.seed(1)
a_matrix <- matrix(sample(0:100, 16), ncol=4)
b_matrix <- matrix(sample(0:100, 16), ncol=4)
dimnames(a_matrix) <- list(rownames(a_matrix, do.NULL = FALSE, prefix = "row"),
colnames(a_matrix, do.NULL = FALSE, prefix = "col"))
dimnames(b_matrix) <- list(rownames(b_matrix, do.NULL = FALSE, prefix = "row"),
colnames(b_matrix, do.NULL = FALSE, prefix = "col"))
a_matrix
col1 col2 col3 col4
row1 26 19 58 61
row2 37 86 5 33
row3 56 97 18 66
row4 89 62 15 42
b_matrix
col1 col2 col3 col4
row1 13 21 86 12
row2 1 77 93 39
row3 44 64 74 47
row4 17 69 80 22
my_list <- list(a_matrix,b_matrix)
Filtering the whole list by:
names <- c("col1", "col2", "row2", "row3")
理想结果
a_matrix
col1 col2
row2 37 86
row3 56 97
b_matrix
col1 col2
row2 1 77
row3 44 64
虽然仍然保留在列表中。
解决方案
list
在with 上循环,使用向量中的lapply
行/列名子集矩阵,names
其中元素 3 到 4 是行名属性,1 到 2 是列名
lapply(my_list, \(x) x[names[3:4], names[1:2]])
-输出
[[1]]
col1 col2
row2 37 86
row3 56 97
[[2]]
col1 col2
row2 1 77
row3 44 64
数据
my_list <- list(structure(c(26L, 37L, 56L, 89L, 19L, 86L, 97L, 62L, 58L,
5L, 18L, 15L, 61L, 33L, 66L, 42L), .Dim = c(4L, 4L), .Dimnames = list(
c("row1", "row2", "row3", "row4"), c("col1", "col2", "col3",
"col4"))), structure(c(13L, 1L, 44L, 17L, 21L, 77L, 64L,
69L, 86L, 93L, 74L, 80L, 12L, 39L, 47L, 22L), .Dim = c(4L, 4L
), .Dimnames = list(c("row1", "row2", "row3", "row4"), c("col1",
"col2", "col3", "col4"))))
推荐阅读
- java - 如何从 Zip 读取 XML 而不提取目录中的 zip
- css - CSS 中的常用类、助手类和实用程序类是什么?
- reactjs - React Page Scroller 不允许 useScrollTrigger 工作(react-page-scroller 和 @material-ui/core)
- kubernetes - 如何在 k8s pod 终端中检查数据库?
- github-actions - Github 在工作服中发布报道的操作始终显示“未知”徽章
- node.js - Node.js MS SQL 事务
- sql-server - 如何验证 ODBC 版本是 odbc.ini 文件中的版本?
- java - 如何在 Java 中读取 JSON 对象的值
- c++ - 如何验证这种格式的数据 UEEW123456
- javascript - 如何在 D3.js 中使用 scaleOrdinal 绘制一条线?