Sequential modification of objects in R

I have several matrices of the same size:

m1.m <- matrix(c(1,2,3,4), nrow=2, ncol=2)
m2.m <- matrix(c(5,6,7,8), nrow=2, ncol=2)
...

      

I want all the same column and row names.

I am currently doing it like this:

new_col_names <- c("Col1","Col2")
new_row_names <- c("Row1","Row2")
change_names <- function(m, new_col_names, new_row_names) {
  colnames(m) <- new_col_names
  rownames(m) <- new_row_names
  return(m)
}
m1.m <- change_names(m1.m, new_col_names, new_row_names)
m2.m <- change_names(m2.m, new_col_names, new_row_names)
...

      

Is there a way to do serial modification (overcoming copying objects when going to functions)? So far I've tried to run the replace function in lapply

; however, it doesn't seem to work.

+3


source to share


1 answer


I would create a list of all your matrices with mget

and ls

(and some regex to match your matrix names) and then change them all at once with lapply

and colnames<-

and rownames<-

the replace function. Some of these lines

l <- mget(ls(patter = "m\\d+.m"))
lapply(l, function(x) {
                       x <- `colnames<-`(x, new_col_names) 
                       `rownames<-`(x, new_row_names)
                      })
# $m1.m
#      Col1 Col2
# Row1    1    3
# Row2    2    4
# 
# $m2.m
#      Col1 Col2
# Row1    5    7
# Row2    6    8

      



It's generally a good idea to keep objects in a list rather than polluting the global environment, so try not to listen to anyone telling you to use list2env

as the next step.

+6


source







All Articles