We can create this in a list
lst <- replicate(8, {id<-c(1,2,3,4,5,6,7,8)
i1<- rbinom(8,1,.5)
i2<- rbinom(8,1,.5)
rt1<-rnorm(8)
rt2<- rnorm(8)
df <- data.frame(id,i1,i2,rt1,rt2)},
simplify = FALSE)
and then access each data.frame using [[
lst[[1]]
lst[[2]]
If we need to create 8 data.frame objects in the global environment, use list2env
(not recommended though)
list2env(setNames(lst, paste0("df", seq_along(lst))), envir =.GlobalEnv)
df1
# id i1 i2 rt1 rt2
#1 1 0 0 -0.10005874 -0.7554699
#2 2 0 1 0.73783083 0.9486937
#3 3 0 0 0.60071808 -0.6073825
#4 4 0 0 1.34181501 -0.7873832
#5 5 1 1 0.74039777 -0.4152928
#6 6 0 0 0.70413214 0.3182971
#7 7 0 1 -1.34215328 0.6912802
#8 8 1 1 0.08427694 0.6138306
df2
# id i1 i2 rt1 rt2
#1 1 0 0 -0.5756818 -1.8153806
#2 2 0 1 0.6438000 0.4386427
#3 3 1 0 0.1849091 0.2079155
#4 4 1 1 1.0915329 0.9173109
#5 5 1 0 -0.6868610 0.2586526
#6 6 0 0 0.6588452 0.8982610
#7 7 1 1 0.7612920 -0.5889034
#8 8 1 1 0.7771745 0.4025183
If we need a for
loop, either create an empty list
of length N (here 8), and assign output from each iteration to it.
lst1 <- vector("list", 8)
for(i in 1:8){
id<-c(1,2,3,4,5,6,7,8)
i1<- rbinom(8,1,.5)
i2<- rbinom(8,1,.5)
rt1<- rnorm(8)
rt2<- rnorm(8)
lst1[[i]] <- data.frame(id,i1,i2,rt1,rt2)
}
or instead of that, we can assign
to a new object name in each iteration so that there will be 8 data.frame objects in the global environment
for(i in 1:8){
id<-c(1,2,3,4,5,6,7,8)
i1<- rbinom(8,1,.5)
i2<- rbinom(8,1,.5)
rt1<- rnorm(8)
rt2<- rnorm(8)
assign(paste0("newdf", i), value= data.frame(id,i1,i2,rt1,rt2))
}
newdf1
# id i1 i2 rt1 rt2
#1 1 1 0 0.18472864 0.5929184
#2 2 1 1 0.72289366 0.9227808
#3 3 0 0 1.67604392 1.1759845
#4 4 0 0 -1.37200571 -1.4740593
#5 5 1 0 -1.60339952 0.7562232
#6 6 1 1 -2.33245352 0.9699605
#7 7 0 0 0.05202936 0.9604707
#8 8 0 0 -0.99444913 0.5079725