2 views

Suppose I have a n by 2 matrix and a function that takes a 2-vector as one of its arguments. I would like to apply the function to each row of the matrix and get a n-vector. How to do this in R?

For example, I would like to compute the density of a 2D standard Normal distribution on three points:

bivariate.density(x = c(0, 0), mu = c(0, 0), sigma = c(1, 1), rho = 0){

exp(-1/(2*(1-rho^2))*(x^2/sigma^2+x^2/sigma^2-2*rho*x*x/(sigma*sigma))) * 1/(2*pi*sigma*sigma*sqrt(1-rho^2))

}

out <- rbind(c(1, 2), c(3, 4), c(5, 6))

How to apply the function to each row of out?

How to pass values for the other arguments besides the points to the function in the way you specify?

by

You can directly use the apply() function to apply a function to each row of a matrix.

For example:

M <- matrix(1:20, nrow=4, byrow=TRUE)

M

[,1] [,2] [,3] [,4] [,5]

[1,]    1    2    3    4    5

[2,]    6    7    8    9   10

[3,]   11   12   13   14   15

[4,]   16   17   18   19   20

apply(M, 1, function(x) x+x+x+x+x)

 15 40 65 90

The apply function above applies the function(x) i.e, to print the sum of elements in each row.