The first step is to create a function object and then use it. If you want the matrix object to have the same number of rows, you can predefine it and use the object [] form, as shown (otherwise the return value will be simplified for the vector):
bvnormdens <- function(x=c(0,0),mu=c(0,0), sigma=c(1,1), rho=0){ exp(-1/(2*(1-rho^2))*(x[1]^2/sigma[1]^2+ x[2]^2/sigma[2]^2- 2*rho*x[1]*x[2]/(sigma[1]*sigma[2]))) * 1/(2*pi*sigma[1]*sigma[2]*sqrt(1-rho^2)) } out=rbind(c(1,2),c(3,4),c(5,6)); bvout<-matrix(NA, ncol=1, nrow=3) bvout[] <-apply(out, 1, bvnormdens) bvout [,1] [1,] 1.306423e-02 [2,] 5.931153e-07 [3,] 9.033134e-15
If you want to use parameters other than the default parameters, then the call must include named arguments after the function:
bvout[] <-apply(out, 1, FUN=bvnormdens, mu=c(-1,1), rho=0.6)
apply () can also be used for arrays with a higher dimension, and the argument MARGIN can be either a vector or a single integer.
Nov 42-21. '10 at 15:01 2010-11-21 15:01
source share