8

Apologies if this is a stupid question - but this my first attempt at using R, and i have ended up writting some code along the lines of:

some <- vector('list', length(files))
thing <- vector('list', length(files))
and <- vector('list', length(files))
another <- vector('list', length(files))
thing <- vector('list', length(files))

Is there a nicer (DRY) way to do this in R?

To rephrase, I want to assign the same value to multiple variables at once (as per @Sven Hohenstein's answer)

rwb
  • 4,309
  • 8
  • 36
  • 59
  • Could you provide a written description of what you're trying to do? I don't think many will understand your mockup. However for variable assignment see: ?assign and it's converse ?get – Brandon Bertelsen Nov 14 '12 at 18:07
  • 4
    This feels like a classic [XY problem](http://meta.stackexchange.com/q/66377/164376). Could you provide more details about what you're actually trying to accomplish? – joran Nov 14 '12 at 18:17
  • I don't feel like this is an XY problem, as i am asking exactly what i am trying to accomplish. I am just interested to know if there is a cleaner way to write the above statement. – rwb Nov 14 '12 at 18:46
  • 3
    The function `vector('list', length(files))` creates a list of length(files) with each element of the list set to `NULL`. This makes me believe that the next thing you are going to do is load a bunch of files into that list using a `for` loop. There are better ways to do this in R. –  Nov 14 '12 at 19:03

2 Answers2

21

If you want to assign the same value to multiple variables at once, use this:

some <- thing <- and <- another <- thing <- vector('list', length(files))
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
0

As an alternative to chaining multiple assignment operators, which appears messy, I suggest using the assign function instead. Here is a small example using a for loop over a vector of desired object names.

vars = c("some","thing","and","another","thing")

for (i in seq_along(vars)) {
  assign(x = vars[i], value = "some_object")
}

ls()
#> [1] "and"     "another" "i"       "some"    "thing"   "vars"
str(some)
#>  chr "some_object"
mhovd
  • 3,724
  • 2
  • 21
  • 47