R Double For Loop
I have an obvious question about doing a double loop in R and could not find an answer on this website. I am using the following code:
mu <- c(0, .2, .5, .8)
sco <- matrix(nrow = 50, ncol = 4*10)
for (mu in mus) {
for (i in 1:10) {
sco[ ,i] <- mu + rnorm(n = 50, mean = 0, sd = 1)
}
}
Now I get 10 columns with mu + random numbers, but what I want to get is 40 columns where the first 10 columns represent mu is 0 + random, columns 11 to 20 represent 0.2 + random etc.
How do I modify my code to get these above results?
Thank you in advance!
source to share
Isn't it that the variance in all columns is the same? Why not create a matrix with 50 * 40 standard-normal random numbers and then add 0 to the first ten columns, 0.2 to the next ten, and so on ?!
EDIT:
An example would look like this:
result <- matrix(rnorm(50*40,mean=0,sd=1),ncol=40)
mu <- c(rep(0,10),rep(10,10),rep(20,10),rep(30,10))
result <- t(t(result) + mu)
I forgot how to add a vector column, so ugly working with 2 transpositions ... And I chose different values โโfor mu
to make the result clearer.
The loop solution would look like this (although I wouldn't use this code, but you asked for it ...)
mus <- c(0, 10, 20, 30)
sco <- matrix(nrow = 50, ncol = 4*10)
for (mu in 1:4) {
for (i in 1:10) {
sco[ ,i+(mu-1)*10] <- mus[mu] + rnorm(n = 50, mean = 0, sd = 1)
}
}
source to share
I would do something like:
return_numbers = function(mu_value) {
matrix(mu_value + rnorm(50 * 10), 50, 10)
}
dat = do.call("cbind", lapply(mu, return_numbers))
and skip the for loop entirely. I skip the first loop by generating all the numbers for the first ten rows at the same time and then resizing the vector to a matrix. I'll skip the second loop using lapply
to iterate over the values mu
. Finally, I use cbind
to put them in one data structure.
source to share