How to apply a function to each entry of a matrix in R

Home / Uncategorized / How to apply a function to each entry of a matrix in R

Question:
I have to store the log likelihood of some densities in a matrix, as follows:Matrix.logLik
[,1] [,2] [,3] [,4] [,5]
[1,] 0.00000 0.0000 0.0000 0.0000 0
[2,] -34.41018 0.0000 0.0000 0.0000 0
[3,] -2275.14867 -765.8642 0.0000 0.0000 0
[4,] 64.96982 264.7709 -256.1461 0.0000 0
[5,] 358.17822 260.1582 427.3490 363.2247 0

I would like to apply AIC function.
AIC.log <- function(x,y=2){ -2*x+2*y } where x is the log likelihood value (the entries of the Matrix.loglik) and y is number of parameters. Then, I would like to store the result in a lower triangular matrix similar to Matrix.loglik. Thank you for all answer. However, my matrix must stay lower triangular matrix. That is the zeros entries in my matrix must still zeros. I try both answer and got this:[,1] [,2] [,3] [,4] [,5] [1,] 4.00000 4.0000 4.0000 4.0000 4 [2,] 72.82036 4.0000 4.0000 4.0000 4 [3,] 4554.29734 1535.7284 4.0000 4.0000 4 [4,] -125.93964 -525.5418 516.2922 4.0000 4 [5,] -712.35644 -516.3164 -850.6980 -722.4494 4 This is not what I should get. number 4 must be zero. Any idea please?


Answer:
You can multiply by `lower.tri` to get desired result:
Matrix.logLik <- c( 0.00000, 0.0000, 0.0000, 0.0000, 0, 34.41018, 0.0000, 0.0000, 0.0000, 0, -2275.14867, -765.8642, 0.0000, 0.0000, 0, 64.96982, 264.7709, -256.1461, 0.0000, 0, 358.17822, 260.1582, 427.3490, 363.2247, 0) Matrix.logLik <- matrix(Matrix.logLik, nrow = 5, byrow = TRUE) AIC.log <- function(x, y = 2){ -2 * x + 2 * y } AIC.log(Matrix.logLik) * lower.tri(Matrix.logLik) # [,1] [,2] [,3] [,4] [,5] #[1,] 0.00000 0.0000 0.0000 0.0000 0 #[2,] -64.82036 0.0000 0.0000 0.0000 0 #[3,] 4554.29734 1535.7284 0.0000 0.0000 0 #[4,] -125.93964 -525.5418 516.2922 0.0000 0 #[5,] -712.35644 -516.3164 -850.6980 -722.4494 0 Another way to do it is to modify AIC.log function:AIC.log <- function(x, y = 2){ m <- -2 * x + 2 * y lower.tri(m) * m } AIC.log(Matrix.logLik) Read more

Leave a Reply

Your email address will not be published. Required fields are marked *