R Keep colnames and rownames when using sapply on a matrix
Asked Answered
H

3

6

A question was already asked on how keeping colnames in a matrix when applying apply, sapply, etc. here. But I didn't find how to keep the column AND row names of a matrix.

Below an example:

mat = matrix(c(as.character(1:4)), nrow = 2)
colnames(mat) = c( 'col1', 'col2' )
rownames(mat) = c( 'row1', 'row2' )
mat = apply(mat,  2,  function(x) as.numeric(paste(x)))
colnames(mat)
rownames(mat)

Thanks in advance :-)

Humpback answered 25/9, 2019 at 12:29 Comment(1)
this question and it's answer might be worth taking a look atIndignation
I
5

We can wrap your application in a user-defined function.

mat_fun <- function(m){
  m2 <- apply(m,  2,  function(x) as.numeric(paste(x)))
  colnames(m2) <- colnames(m)
  rownames(m2) <- rownames(m)
  return(m2)
}

mat_fun(mat)
#      col1 col2
# row1    1    3
# row2    2    4
Intension answered 25/9, 2019 at 12:34 Comment(1)
Very clever! He had to think. Thank you very much ;-)Humpback
H
4

If you reassign using [], the names are preserved. Unfortunately, this is only useful when you don't want to create a new matrix and also don't want to change the class of the elements (e.g. from character to numeric as in this example)

mat[] <- apply(mat,  2,  function(x) 1 + as.numeric(paste(x)))
mat
#      col1 col2
# row1 "2"  "4" 
# row2 "3"  "5" 
Hallel answered 25/9, 2019 at 13:16 Comment(1)
Thanks for this precision. This method may be very useful on some operations.Humpback
B
0

Based on @Humpelstielzchen's comment, here's my alternative:

mat = apply(mat, 2, function(x) setNames(as.numeric(paste(x)), names(x)))

Basically, as apply is working in row-wise manner (ie, every row is considered separately as a vector) we must name our new vector as we created it... and for that, setNames is a wonderful option.

Backwardation answered 24/5, 2023 at 7:45 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.