gpt4 book ai didi

r - `rowname` - 矩阵列表

转载 作者:行者123 更新时间:2023-12-02 12:19:22 24 4
gpt4 key购买 nike

假设我有一个名为 Tables 的矩阵列表,其中包含列名但不包含行名。

 Tables <- list(structure(c(0.810145949194718, 0.0792559803788517, 0.189854050805282, 
0.920744019621148), .Dim = c(2L, 2L), .Dimnames = list(NULL,
c("e", "prod"))), structure(c(0.949326264941026, 0.24010922539329,
0.0506737350589744, 0.75989077460671), .Dim = c(2L, 2L), .Dimnames = list(
NULL, c("prod", "e"))))

我希望行名与列名相同:

rownames(Tables[[1]])<- colnames(Tables[[1]])
rownames(Tables[[2]])<- colnames(Tables[[2]])

我尝试使用lapply但没有成功

lapply(Tables, function(x) rownames(x) <- colnames(x))

我设法使用 for 循环来做到这一点

for(i in 1:length(Tables)){
rownames(Tables[[i]])<- colnames(Tables[[i]])
}

Tables # Expected result
[[1]]
e prod
e 0.81014595 0.1898541
prod 0.07925598 0.9207440

[[2]]
prod e
prod 0.9493263 0.05067374
e 0.2401092 0.75989077

尽管如此,我想找到一种方法来使用任何 *apply 或基类中的任何其他函数来避免 for 循环,但我无法成功在这个目标上。我读过this但我不知道如何使用这些解决方案。有什么建议吗?

最佳答案

lapply(Tables, function(x){
rownames(x) <- colnames(x)
x
})

# [[1]]
# e prod
# e 0.81014595 0.1898541
# prod 0.07925598 0.9207440
#
# [[2]]
# prod e
# prod 0.9493263 0.05067374
# e 0.2401092 0.75989077

关于r - `rowname` - 矩阵列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19123612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com