`rowname`-一个矩阵列表

时间:2013-10-01 18:46:16

标签: r rowname

假设我有一个名为Tables的矩阵列表,其中包含colnames且没有rownames。

 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与colnames相同:

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但我无法弄清楚如何使用这些解决方案。有什么建议??

4 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:5)

另一种选择:

for (x in Tables) 
   data.table::setattr(x, "dimnames", list(colnames(x), colnames(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

答案 2 :(得分:4)

R已经拥有您需要的一切: - )

Tables <- Map(`rownames<-`, Tables, lapply(Tables, colnames))

答案 3 :(得分:1)

这是一种方式:

lapply(seq_along(Tables), function(i) {
    rownames(Tables[[i]]) <<- colnames(Tables[[i]])
    return(invisible())
})

......这很难看 - 使用循环代替。或者,如果您确实想要使用lapply,请尝试:

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

有人早些时候发布了此消息,但他们似乎已删除了答案。

相关问题