Search code examples
rdataframematrixapplysapply

R Keep colnames and rownames when using sapply on a matrix


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


Solution

  • 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