1

I would like to automatically create a number of elements inside a for loop, but still have them when the loop ends. The elements have to be named based on the loop variable.

for(i in letters){
  paste(c('student', i), collapse = '') = classroom[i]
}

however i get the following error message:

paste(c('student', i), collapse = '') = classroom[i] : 
  target of assignment expands to non-language object

is there a way to create and name new objects inside a for loop based on the loop variable?

Phil
  • 7,287
  • 3
  • 36
  • 66
  • 2
    Do not do this, I REPEAT, do not do this. Consider having everything in a container eg list/vector/matrices etc. But do not pollute the global environment with thousands of variables. Note that you can do this, but will it be worth it? – Onyambu Apr 04 '23 at 17:57
  • Agreed - this points to a bad workflow. I have a hard time thinking why this would be a better approach over just storing elements into a list. – Phil Apr 04 '23 at 18:04
  • 1
    I ended up making a list. To everyone worried I know it would pollute the environment, however in this case I just wanted to make 12 objects so wasn't that worried – Caio Théodore Apr 04 '23 at 18:14
  • @CaioThéodore It would certainly not pollute the env. – akrun Apr 04 '23 at 18:24

0 Answers0