Question

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??

Was it helpful?

Solution

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

OTHER TIPS

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

R already has everything you need :-)

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

Here's one way:

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

...which is ugly -- use a loop instead. Or, if you do want to use lapply, try:

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

Someone posted this earlier but they seem to have deleted their answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top