Search code examples
rloopsnormal-distribution

how to use mvrnorm for multiple mean vector in R


mu is the matrix of two mean vectors (col-1 and col-2 are two mean vectors)

mu=matrix(c(1,5,4,
                5,8,9), nrow =3,ncol=2)
mu
         [,1] [,2]
    [1,]    1    5
    [2,]    5    8
    [3,]    4    9

And the corresponding covariance matrices are as

sig1=matrix(c(diag(1,3,3),
            diag(4,3,3)), nrow = 3, ncol = 3*2, byrow = F)
sig1
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    0    0    4    0    0
[2,]    0    1    0    0    4    0
[3,]    0    0    1    0    0    4

The first three column is the covarince matrix for mean vector-1(i,e col-1 of mu) and last three is for mean vector-2(i,e, col-2 of mu) I would like to use mvrnorm to generate data for each mean vector and covariance matrix

I would like to create a matrix of order 2 by 3 where the first row is the output of mvrnorm(1,mu[,1],sig1[,1:3]) and the second row is the output of mvrnorm(1,mu[,2],sig1[,4:6]) Can I do it using any loop or bulit-in function? Any help is appreciated


Solution

  • You can create a sequence to subset mu at every column and sig1 every 3 columns and pass it to mvrnorm function.

    t(sapply(seq_len(ncol(mu)), function(x) {
       ind <- (x - 1) * 3 
       MASS::mvrnorm(1,mu[,x],sig1[, (ind + 1):(ind + 3)])
    }))
    
    #       [,1]   [,2]   [,3]
    #[1,] 1.0665 3.5964 4.4052
    #[2,] 4.9421 9.7464 9.6109