Search code examples
rexpressiondistribution

How to find an algebraic expression from an R code?


I have the below codes for a bivariate normal distribution:

library(mnormt)

x     <- seq(-5, 5, 0.25) 
y     <- seq(-5, 5, 0.25)
mu    <- c(0, 0)
sigma <- matrix(c(2, -1, -1, 2), nrow = 2)
f     <- function(x, y) dmnorm(cbind(x, y), mu, sigma)
z     <- outer(x, y, f)

a) I would like to know what the algebraic expression z=f(x,y) is based on the above codes (please write the algebraic expression explicitly). b) Indeed, numbers 2, -1, -1 and 2 in matrix(c(2, -1, -1, 2), nrow = 2) are which parameters in the algebraic expression z=f(x,y)?


Solution

  • If you want to see the source code, you may go to see there there. I comment the code for you :

    dmnorm <- function(x, mean=rep(0,d), varcov, log=FALSE)
    {
        # number of variable
        d <- if(is.matrix(varcov)) ncol(varcov) else 1
        
        if(d==1) return(dnorm(x, mean, sqrt(varcov), log=log))
        
        x <- if (is.vector(x)) t(matrix(x)) else data.matrix(x)
        
        if(ncol(x) != d) stop("mismatch of dimensions of 'x' and 'varcov'")
        
        if(is.matrix(mean)) {
            if ((nrow(x) != nrow(mean)) || (ncol(mean) != d))
            stop("mismatch of dimensions of 'x' and 'mean'") }
        
        if(is.vector(mean)) mean <- outer(rep(1, nrow(x)), as.vector(matrix(mean,d)))
        
        # center 
        X  <- t(x - mean)
        
        # compute the inverse of sigma
        conc <- pd.solve(varcov, log.det=TRUE)
        
        # Q is the exponential part
        Q <- colSums((conc %*% X)* X)
        
        # compute the log determinant
        log.det <- attr(conc, "log.det")
        
        # log likelihood
        logPDF <- as.vector(Q + d*logb(2*pi) + log.det)/(-2)
        
        if(log) logPDF else exp(logPDF)
    }
    

    It is a strick application of this equation :

    enter image description here

    Which come from this website.