So I have 2 variables a and d with 3 possible values. So there can be 9 Combinations of the 2. I wanna save the output of the following nested for loop in separate lists. How do I do that? The result should be 9 lists with the values as and ds together
for (d in c(0.5,1,2)){
for (a in c(0.05,0.1,0.2)){
as<-c(rnorm(5,mean=1, sd=a))
ds<-c(rnorm(5,mean=0, sd=d))
}
}
CodePudding user response:
You do not describe your desired output very exactly, but you can try the following to get a list of nine lists:
lapply(c(0.5,1,2), function(d){
lapply(c(0.05,0.1,0.2), function(a){
list(as = rnorm(5,mean=1, sd=a), ds = rnorm(5,mean=0, sd=d) )
})
})
CodePudding user response:
You don't need loops at all here. The sd
argument of rnorm
is vectorized, so you can do:
as <- split(rnorm(45, 1, sd = rep(c(0.05,0.1,0.2), each = 3)), 0:44 %/% 5)
ds <- split(rnorm(45, 1, sd = rep(rep(c(0.5,1,2), each = 3), each=3)), 0:44 %/% 5)
Now as
and ds
will each be a list of nine length-5 random vectors with the appropriate values.