Search code examples
robjectnaming

name objects from vector values


I'm trying to use the character values of a vector to name new objects and then make those new objects into new matrices. So if I have the following vector:

Named <- c("a", "b", "c")

I want to be have a loop to make objects named "a", "b", and "c"

for(i in 1:length(Named)){
Named[i] <- matrix(0L, nrow = 3, ncol = 3)
}

I realize that this code currently inputs data into the vector. How do I extract the characters at Named[i] to use as the name of the new objects?

So that the loop does the same thing as writing this code:

a <- matrix(0L, nrow = 3, ncol = 3)
b <- matrix(0L, nrow = 3, ncol = 3)
c <- matrix(0L, nrow = 3, ncol = 3)

Solution

  • 1) assign Normally one would want to assign the values into a list but if you must assign them into the global environment then this is a good application for a for loop:

    for(nm in Named) assign(nm, matrix(0L, 3, 3), .GlobalEnv)
    

    If you are already doing this at the global environment level then you could optionally omit the last argument to assign.

    2) index global environment This would also work:

    for(nm in Named) .GlobalEnv[[nm]] <- matrix(0L, 3, 3)
    

    3) list2env Another approach is to create a list then use list2env to copy its components to the global environment.

    list2env( Map(function(x) matrix(0L, 3, 3), Named), .GlobalEnv )
    

    4) hard coding Note that if you just have a few elements to assign and you don't need to parameterize by a variable such as Named you could just hard code it like this:

    a <- b <- c <- matrix(0L, 3, 3)
    

    5) list If in the end you do decide to create a list instead of objects in the global environment then:

    L <- Map(function(x) matrix(0L, 3, 3), Named)