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)

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 ?get Commented Nov 14, 2012 at 18:07
  • 5
    This feels like a classic XY problem. Could you provide more details about what you're actually trying to accomplish? Commented Nov 14, 2012 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. Commented Nov 14, 2012 at 18:46
  • 4
    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. Commented Nov 14, 2012 at 19:03

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.