Victor Proon
Victor Proon

Reputation: 271

dmnorm() function with multiple means

I've been searching the answer but didn't find any information about this function except the off. R docs.

If i want to calculate the values of 1-dimentional normal distribution in the same x with different means or standard deviations i'll just call

dnorm(x, mu, sigma)

where mu and sigma will be arrays with desired means and sigmas. Is there any way to perform same trick with dmnorm function from mnormt module, when x and mu are vectors and sigma is a covariation matrix?

P.S.: Sorry for my English, thanks for answers.

Upvotes: 1

Views: 1428

Answers (1)

IRTFM
IRTFM

Reputation: 263362

In R the collections of functions are called "packages". If a function is not vectorized in its parameters, you can pass it one parameter as a vector with sapply or as a parallelized set of list with mapply. So you should consider the mathematical issue, especially that the 'mean' is no longer a single number but rather a vector, and that sigma (which dmnorm is calling 'varcov')is no longer a single number but rather a matrix. The first example in the help page gives you the densities of 21 different x,y,z's and a single mean vector and sigma matrix.

Using that example as a starting point, make a list of 7 x,y,x and 7 varying means and sigmas and then mapply it to the first 7 items in the xyz's :

 x <- seq(-2,4)
 y <- 2*x+10
 z <- x+cos(y) 
 mu <- c(1,12,2)
Sigma <- matrix(c(1,2,0,2,5,0.5,0,0.5,3), 3, 3) 
lsig <- lapply(seq(-2,4)/10, "+", Sigma);  lmean<-lapply(seq(-2,4)/10, "+",mu)

mapply(dmnorm, x=as.data.frame(t(cbind(x,y,z)[1:7,])), mean=lmean,  varcov=lsig)
#        V1        V2        V3        V4        V5        V6        V7 
# 6.177e-06 6.365e-04 5.364e-03 3.309e-02 2.205e-02 6.898e-03 1.077e-03 

Upvotes: 3

Related Questions