How to create objects (variables) with different names within a loop?

I want to generate distinct databases in a loop. In the example below would be 3 distinct bases with the following names: "data1", "data2", "data3".

for (n in 1:3){
  dados<-paste0("dados",n)
  dados<-runif(10,1,20)}

However when running the code only one object with the name "data" is generated instead of the three.

How do I make R understand that I want to assign the values to objects created in the loop?

Author: Carlos Cinelli, 2014-03-06

1 answers

You can use the function assign for this.

set.seed(1)
for (i in 1:3){
  nome <- paste0("dados", i)
  assign(nome, runif(10,1, 20))
}

The first part nome <- paste0("dados", i) creates the variable name. The second part assign(nome, runif(10,1, 20)) assigns a value to the variable whose name will be taken from nome.

I wrote the variable nome separately to better explain the function, but you could leave the paste inside the direct assign: assign(paste0("dados", i), runif(10,1, 20)).

 8
Author: Carlos Cinelli, 2014-03-06 22:04:01