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


i have store log likelihood of densities in matrix, 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 apply aic function.

aic.log <- function(x,y=2){   -2*x+2*y } 

where x log likelihood value (the entries of matrix.loglik) , y number of parameters. then, store result in lower triangular matrix similar matrix.loglik.

thank answer. however, matrix must stay lower triangular matrix. zeros entries in matrix must still zeros.

i try both answer , 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 not should get.

number 4 must zero. idea please?

you can multiply `lower.tri` 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 modify aic.log function:

aic.log <- function(x, y = 2){   m <- -2 * x + 2 * y   lower.tri(m) * m }  aic.log(matrix.loglik) 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -