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

10

I want to generate separate databases in a loop. In the example below there 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 you run the code, only an object named "data" is generated instead of the three.

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

    
asked by anonymous 06.03.2014 / 22:33

1 answer

6

You can use the assign function to do 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 name of the variable. 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 explain the function better, but you could leave paste within assign direct: assign(paste0("dados", i), runif(10,1, 20)) .

    
06.03.2014 / 22:37