# Use vector elements as object names in loop.

I have a vector called keys with 10 character elements:
[1] "PL0501" "PL0502" "PL0503" "PL0504" "PL0505" "PL0506" "PL0507" "PL0508" "PL0509" "PL0510"
I want to use these elements as matrix names within a loop that is dynamically creating matrices.

for (i in 1:nrow(df1)) {
keys[i] <- matrix(nrow = 6, ncol = 6)
etc......

Of course this doesn't work as R thinks I want to assign a 6x6 matrix to keys[i] !
Is there a function I can use here that will simply read the value of keys[i] in the loop and use this as the matrix name? I don't need help creating the matrices, just naming them in this fashion. The values in the list will often change in the program so I can't hard code them. I need a function that will allow me to name them dynamically but can't find one.

Thanls in advance to anyone that can help.

Take a look at the assign() function. I think it does what you want.

Thanks. I'm not exactly sure how to apply the assign function here. It is used to assign a value to a variable name. So if I create a matrix say x <- matrix(nrow = 6, ncol = 6) then assign("x", keys[i]). x becomes a one element character vector and is no longer a matrix. I have tried using the paste function also. It seems difficult just to extract the value of keys[i] and simply use this as an object name.

I was thinking to use assign as in the following code. Perhaps I misunderstood.

keys <- paste0("PL050", 1:4)
keys
#> [1] "PL0501" "PL0502" "PL0503" "PL0504"
for (i in 1:4) {
x = matrix(i, ncol = i, nrow = i)
assign(keys[i], x)
}
print(PL0503)
#>      [,1] [,2] [,3]
#> [1,]    3    3    3
#> [2,]    3    3    3
#> [3,]    3    3    3
print(PL0502)
#>      [,1] [,2]
#> [1,]    2    2
#> [2,]    2    2

Created on 2020-10-15 by the reprex package (v0.3.0)

Thanks for your help. I misunderstood how the assign function works.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.