[R] generate multiple mvrnorm samples using apply-like

Michael Friendly friendly at yorku.ca
Sun May 8 00:34:47 CEST 2011


I want to generate multiple multivariate normal samples with different 
mean vectors
and common covariance matrix.
I can do this with a loop, but can't quite figure out how to do it with 
apply and friends.
In the example below, I want values to have 3 columns: group, x, y

# number of groups, and group means
x <- jitter(seq(2,10,by=2))
y <- x + rnorm(length(x), 0, .5)
means <- cbind(x,y)
Sigma <- matrix(c(6,3,3,2),2,2)

# loop version
n<- 10
values <- NULL

for (i in 1:length(x)) {
     val <- mvrnorm(n, means[i,], .5*Sigma, empirical=TRUE)
     values <- rbind(values, val)
}
group <- factor(rep(letters[1:length(x)], each=n))
values <- cbind(group=group, values)

 > str(values)
  num [1:50, 1:3] 1 1 1 1 1 1 1 1 1 1 ...
  - attr(*, "dimnames")=List of 2
   ..$ : NULL
   ..$ : chr [1:3] "group" "x" "y"

# trying apply
vals <- apply(means, 1, function(x) mvrnorm(n, x, Sigma, empirical=TRUE))
str(vals)
head(vals)

But this gives me a 20 x 5 matrix, with the groups as columns and 10 
pairs of rows
representing x, y values.

 > str(vals)
  num [1:20, 1:5] 4.055 -0.124 3.469 -1.169 0.872 ...
 > head(vals)
            [,1]      [,2]     [,3]      [,4]      [,5]
[1,]  4.0551667  4.640607 8.448465 11.795849 12.117418
[2,] -0.1242431  2.480197 7.496188  3.140649 11.473915
[3,]  3.4688356 -0.415469 5.709368  8.188018  6.832460
[4,] -1.1691558  6.579454 2.153095 10.607982  9.053140
[5,]  0.8722773  5.121265 2.168577  7.392535  6.557844
[6,]  7.2737826  2.583776 9.490320  8.144200 11.243709
 >

-- 
Michael Friendly     Email: friendly AT yorku DOT ca
Professor, Psychology Dept.
York University      Voice: 416 736-5115 x66249 Fax: 416 736-5814
4700 Keele Street    Web:   http://www.datavis.ca
Toronto, ONT  M3J 1P3 CANADA



More information about the R-help mailing list