【发布时间】:2023-03-16 09:22:01
【问题描述】:
我有一个矩阵列表,该列表已被网络抓取。我希望按行名和列名过滤每个矩阵。我可以按行名和列表过滤矩阵,但不能按列表中的矩阵!
一些数据
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
虽然仍保留在列表中。
【问题讨论】:
-
试试
lapply(my_list, \(x) x[names[3:4], names[1:2]]) -
您的代码不起作用,
rmatrix是什么?并且在涉及随机过程时始终使用set.seed(),以使结果可重现。
标签: r list matrix filter subset