将“dimnames”分配给列表中的所有矩阵时出错
我在这个线程中使用了解决方案 将暗名称分配给矩阵列表在 R 中,但我没有得到我需要的东西。
我有一个包含 4 个矩阵的列表,我想将它们的列和行命名为相同的名称。
A = list(a = matrix(1:4, 2), b = matrix(2:5, 2))
G = list(a = matrix(10:13, 2), b = matrix(5:8, 2))
M_1 = list(a = matrix(10:13, 2), b = matrix(5:8, 2))
M_2 = list(a = matrix(2:5, 2), b = matrix(5:8, 2))
dlist4 <- tibble::lst(A, G, M_1, M_2)
Map(function(x) {dimnames(x) <- list(c("seed","plant"), c("seed","plant")); x}, dlist4)
并
lapply(dlist4, function(x) {dimnames(x) = list(c("seed","plant"), c("seed","plant")); x})
返回相同的错误: dimnames(x) <- list(c("seed", "plant"), c("seed", "plant")) 中的错误: 'dimnames' 应用于非array
我在这里尝试了循环
R:更改列表中每个矩阵的列名称,也一样,但没有用。
for(i in seq_along(dlist4)) {
dimnames(dlist4[[i]]) <- list(c("seed","plant"), c("seed","plant"))
}
dimnames(dlist4[[i]]) <- list(c("seed", "plant"), c("seed", "plant")) 中的错误:'dimnames' 应用于非数组
I used the solution in this thread assign dimnames to a list of matrices in R but I didn't get what I need.
I have a list of 4 matrices that I wanted to name their columns and rows the same.
A = list(a = matrix(1:4, 2), b = matrix(2:5, 2))
G = list(a = matrix(10:13, 2), b = matrix(5:8, 2))
M_1 = list(a = matrix(10:13, 2), b = matrix(5:8, 2))
M_2 = list(a = matrix(2:5, 2), b = matrix(5:8, 2))
dlist4 <- tibble::lst(A, G, M_1, M_2)
Map(function(x) {dimnames(x) <- list(c("seed","plant"), c("seed","plant")); x}, dlist4)
and
lapply(dlist4, function(x) {dimnames(x) = list(c("seed","plant"), c("seed","plant")); x})
returned the same error: Error in dimnames(x) <- list(c("seed", "plant"), c("seed", "plant")) : 'dimnames' applied to non-array
I tried the loop
here R: change column names of every matrix in a list, too but it didn't work.
for(i in seq_along(dlist4)) {
dimnames(dlist4[[i]]) <- list(c("seed","plant"), c("seed","plant"))
}
Error in dimnames(dlist4[[i]]) <- list(c("seed", "plant"), c("seed", "plant")) : 'dimnames' applied to non-array
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的主列表中没有矩阵,您有另一组列表 - 请参阅
lapply(dlist4, class)
。所以它不是 4 个矩阵,而是 4 组两个矩阵,每个矩阵都在一个列表中。在这种情况下,您需要递归地向下直到停止点击列表,这意味着
rapply
可能会很方便:You don't have a matrix inside your main list, you have another set of lists - see
lapply(dlist4, class)
. So it's not 4 matrices, it's 4 sets of two matrices, each in a list.In this instance, you need to recursively go down until you stop hitting lists, which means
rapply
might be handy:由于您没有矩阵列表,而是矩阵列表列表,因此您必须使用嵌套
lapply()
或嵌套循环:或者,您也可以使用
purrr::map_depth()
专为嵌套列表而设计:由 reprex 包 (v2.0.1)
Since you don't have a list of matrices, but a list of lists of matrices, you will have to use a nested
lapply()
or a nested loop:Alternatively, you could also use
purrr::map_depth()
which is design specifically for nested lists:Created on 2022-03-25 by the reprex package (v2.0.1)