Reputation: 995
I would like object names (character data) to be updated in the for loop, but I'm not sure how to append the indexing variable to the character data. The (obviously incorrect) code that I would have liked to work is:
for(i in 1:5){
name.i <- i
}
The intended output would be equivalent to the following:
name.1 <- 1
name.2 <- 2
name.3 <- 3
name.4 <- 4
name.5 <- 5
I'm not even sure what this problem would be called --- please let me know (if you know) so that I can appropriately title future questions.
EXTENSION
Say that the working code produces vectors instead of numbers, but we require a for loop that loops through each of the name.i
vectors and changes one of their entries. How might we keep the indexing of the i
in name.i
in this for loop? That is, how might one condense the following:
for(i in 1:5){
assign(paste0("name.", i), c(i, 0, 0))
}
name.1[2] <- 1 + 1
name.2[2] <- 2 + 1
name.3[2] <- 3 + 1
name.4[2] <- 4 + 1
name.5[2] <- 5 + 1
Of course, the second entry in the original for loop could be set as i+1
, but I am interesting in understanding how to use character names in this way ---
that is, by looping through the names using an indexing parameter, although the names themselves are character data (if it's possible).
Upvotes: 1
Views: 153