Apostolos Polymeros
Apostolos Polymeros

Reputation: 843

R: creating a variable on the fly

I would like to ask for some help in creating a sequence of variables v1,v2,... while running a program. I run the following code for one such variable:

FinishAt <- 1
Sequence <- 1:FinishAt
AsCharacterSequence <- as.character(Sequence)

aa <- paste("v", AsCharacterSequence[1], sep="", collapse="") # [1] "v1"
bb <- eval(substitute(variable), list(variable=as.name(a))) # v1

The problem I face is how we shall make v1 a variable with a value (let's say 5).

Thank you in advance.

Upvotes: 2

Views: 1960

Answers (1)

Karsten W.
Karsten W.

Reputation: 18500

You can define variables on the fly with assign. For example, the following generates three variables v1 ... v3:

var_names <- paste("v", 1:3, sep="")
for (v in var_names) assign(v, runif(1))

The counterpart to assign is get, that is, if you want the values of the variables, use something like:

bb <- sapply(var_names, get)

Also note that both assign and get have an optional envir parameter, which enables you to keep those variables away from the rest of your code.

I am not sure, but I think it is possible that if there are many variables, assign/get is faster than a list, at least if you want to look up some values.

Upvotes: 4

Related Questions