Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 362
rwb Avatar asked Nov 14 '12 18:11

rwb


People also ask

Can you assign multiple variables in R?

For instance, create a 1 row dataframe (say V ) and initialize your variables in it. Now you can assign to multiple variables at once V[,c("a", "b")] <- values[c(2, 4)] , call each one by name ( V$a ), or use many of them at the same time ( values[c(5, 6)] <- V[,c("a", "b")] ).

How do I assign multiple variables to the same value in R?

You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.

What is the difference between variable declaration and variable assignment?

Declaration says, "I'm going to use a variable named " a " to store an integer value." Assignment says, "Put the value 3 into the variable a ." (As @delnan points out, my last example is technically initialization, since you're specifying what value the variable starts with, rather than changing the value.

How do we assign variable to R?

In R programming, assign() method is used to assign the value to a variable in an environment. Return : Return the variable having value assigned.


1 Answers

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

some <- thing <- and <- another <- thing <- vector('list', length(files))
like image 154
Sven Hohenstein Avatar answered Sep 23 '22 06:09

Sven Hohenstein