+2 votes
in Programming Languages by (40.7k points)
Suppose I want to generate variables v1, v2, v3,... at the run time by adding 1, 2, 3,... to 'v'. Also, I need to assign some values to these variables at the run time. How can I do it?

1 Answer

+2 votes
by (1.5k points)
selected by
 
Best answer

You can use the assign() function to assign some value to a variable. To create a variable v1, v2,... at run time, you can use the paste0() function.

Here is an example:

for (i in seq(1,5,1)){

  assign(paste0("v", i), i*2) 

}

The above code will generate variables at run time and will assign values to them.

> v1

[1] 2

> v2

[1] 4

> v3

[1] 6

> v4

[1] 8

> v5

[1] 10 


...