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]]
) )
答案 0 :(得分:3)
将每个参数放在列表中的相同参数中:
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
这相当于:
result <- numeric(length(x))
for (i in 1:length(x))
result[i] <- dmvnorm(x[[i]], u[[i]], sigma[[i]])