Mass variable declaration and assignment in R?
Asked Answered
H

2

10

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)

Herlindaherm answered 14/11, 2012 at 18:5 Comment(4)
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 ?getBurble
This feels like a classic XY problem. Could you provide more details about what you're actually trying to accomplish?Centigram
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.Herlindaherm
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.Cornelison
C
24

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

some <- thing <- and <- another <- thing <- vector('list', length(files))
Cryptanalysis answered 14/11, 2012 at 18:32 Comment(0)
G
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"
Giblet answered 21/8, 2023 at 11:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.