[R] Loop avoidance in simulating a vector

David Afshartous dafshartous at med.miami.edu
Thu Oct 16 21:47:17 CEST 2008


I'd like to simulate a vector that is formed from many distinct
distributions and avoid a loop if possible.  E.g, consider:

mu = c(1, 2, 3)
sigma = c(1, 2, 3)
n = c(10, 10, 10)

And we simulate a vector of length 30 that consists of N(mu[i], sigma[i])
distributed data, each of length n[i].   Of course for just three groups we
can simply write it out as:

DV = c(rnorm(n[1], mu[1], sigma[1]), rnorm(n[2], mu[2], sigma[2]),
rnorm(n[3], mu[3], sigma[3]) )

For many groups we can use a loop (assuming equal numbers per group):

n = n[1]
DV = numeric(N*n)
for (i in 1:N) {
    DV[(n*i - (n-1)): (n*i)] = rnorm(n, mu[i], sigma[i])

Is there any way to do the general cas without using a loop?


More information about the R-help mailing list