rwb
rwb

Reputation: 4478

Mass variable declaration and assignment in R?

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)

Upvotes: 10

Views: 8574

Answers (2)

mhovd
mhovd

Reputation: 4067

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"

Upvotes: 0

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

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

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

Upvotes: 24

Related Questions