Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`rowname`-ing a list of matrices

Tags:

r

rowname

Suppose I have a list of matrices called Tables with colnames and without 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"))))

I want the rownames to be the same as the colnames:

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

I've tried using lapply with no success

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

I managed to do it using a for loop

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

Nevertheless, I want to find a way to do it using any *apply or any other function in base to avoid the for loop, but I can't succeed on this target. I read this but I can't figure out how to use any of those solutions. Any suggestion??

like image 621
Jilber Urbina Avatar asked Oct 01 '13 18:10

Jilber Urbina


2 Answers

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
like image 69
Henrik Avatar answered Sep 27 '22 21:09

Henrik


Another option:

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
like image 21
Ricardo Saporta Avatar answered Sep 27 '22 21:09

Ricardo Saporta