简体   繁体   中英

how to use the dmvnorm function and mapply together

set.seed(1)
### i would like to do this
dmvnorm(c(.5,.5), mean= c(2,15), matrix(c(3, 0, 0, 9), 2))
dmvnorm(c(.6,.6), mean= c(5,18), matrix(c(6, 0, 0, 15), 2))

##### BUT using mapply instead... how can that be done?
u1 = c(2,15)
sigma1 = matrix(c(3, 0, 0, 9), 2)
u2 = c( 5, 18)
sigma2 = matrix(c(6, 0, 0, 15), 2)
parameters = list(mu = list(u1, u2), sigma = list(sigma1, sigma2))
mapply( c(c(.5,.5),c(.6,.6)),   dmvnorm, 
        mean = c(parameters$mu[[1]], parameters$mu[[2]] ) ,
        sigma= c(parameters$sigma[[1]],parameters$sigma[[2]] 

) )

Put every parameters to the same argument in a list:

library(mvtnorm)
u <- list(u1 = c(2,15), u2 = c( 5, 18))
sigma <- list(sigma1 = matrix(c(3, 0, 0, 9), 2),
              sigma2 = matrix(c(6, 0, 0, 15), 2))
x <- list(c(0.5, 0.5), c(0.6, 0.6))
result <- mapply(dmvnorm, x, u, sigma)
# [1] 1.780234e-07 1.384004e-07

This is equivalent to:

result <- numeric(length(x))
for (i in 1:length(x))
  result[i] <- dmvnorm(x[[i]], u[[i]], sigma[[i]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM