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

Asked

Viewed 2,292 times

12

I want to generate different databases in a loop. In the example below would be 3 distinct databases 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 to make R understand that I want to assign values to objects created in the loop?

1 answer

8


You can use the function assign for that reason.

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 removed from nome.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.