5

I'd like to use the value of a variable as part of the name of an object to make the creation of new objects with names that I don't have to list out explicitly. An example:

Here is what I don't want to do, declare every single name for 10 objects going down the list from 1 to 10.

a=41:50

a1=a[1]
a2=a[2]
a3=a[3]
a4=a[4]
a5=a[5]
a6=a[6]....

Here is what would make more sense - just putting the name some how as "a" and then combined with the value of i in the loop. Does the same thing, creates 10 objects.

for(i in 1:10){
a#paste.in.the.value.of.i.somehow...=a[i]
}

Thanks for you help!

user311020193
  • 327
  • 2
  • 4
  • 10
  • 6
    There should be no need to do this at all. Creating a bunch of different variable names like that is almost always a mistake. You should keep them in some sort of collection, whether a vector or list. You can have named elements in either. They are just as easy, if not easier, to work with than having bunches of different variables. – MrFlick Aug 09 '14 at 19:43

1 Answers1

3
 for(i in 1:10) {assign(paste0("a", i), a[i])}
 a1
 #[1] 41
 a2
 #[1] 42
 a3
 #[1] 43
akrun
  • 874,273
  • 37
  • 540
  • 662