4

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 :-)

Flora Grappelli
  • 539
  • 6
  • 24
  • [this](https://stackoverflow.com/questions/15229199/r-rownames-colnames-dimnames-and-names-in-apply) question and it's answer might be worth taking a look at – Humpelstielzchen Sep 25 '19 at 12:37

2 Answers2

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
www
  • 37,164
  • 12
  • 37
  • 72
1

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" 
IceCreamToucan
  • 26,789
  • 2
  • 15
  • 32