The following is a function that, by default, will take any objects in the parent environment that have a name that starts with a
followed by numbers, check that they are one column matrices, and if they are, name the columns with the name of the object.
a1 <- matrix(c(1:5))
a2 <- matrix(c(1:5))
name_cols()
a1
# a1
# [1,] 1
# [2,] 2
# ...
a2
# a2
# [1,] 1
# [2,] 2
# ...
And here is the code:
name_cols <- function(pattern="^a[0-9]+", env=parent.frame()) {
lapply(
ls(pattern=pattern, envir=env),
function(x) {
var <- get(x, envir=env)
if(is.matrix(var) && identical(ncol(var), 1L)) {
colnames(var) <- x
assign(x, var, env)
} } )
invisible(NULL)
}
Note I chose specification by pattern, but you can easily change this to be by specifying the names of the variable (instead of using ls
, just pass the names and lapply
over those), or potentially even the objects
(though you have to use substitute for that, and the wiseness of this becomes questionable).
More generally, if you have several related objects on which you will be performing related analysis (e.g. in this case modifying columns), you should really consider storing them in lists rather than at the top level. If you do this, then you can easily use the built in *pply
functions to operate on all your objects at once. For example:
a.lst <- list(a1=matrix(1:5), a2=matrix(1:5))
a.lst <- lapply(names(a.lst), function(x) {colnames(a.lst[[x]]) <- x; a.lst[[x]]})