Search code examples
rlistelementdiagonal

Extract elements from matrix diagonal saved in multiple lists in R


I´m trying to get different elements from multiple diagonal saved as lists. My data looks something like this:

res <- list()
res[[1]] <- matrix(c(0.04770856,0.02854005,0.02854005,0.03260190), nrow=2, ncol=2)
res[[2]] <- matrix(c(0.05436957,0.04887182,0.04887182, 0.10484454), nrow=2, ncol=2)

> res
[[1]]
           [,1]       [,2]
[1,] 0.04770856 0.02854005
[2,] 0.02854005 0.03260190

[[2]]
           [,1]       [,2]
[1,] 0.05436957 0.04887182
[2,] 0.04887182 0.10484454

> diag(res[[1]])
[1] 0.04770856 0.03260190
> diag(res[[2]])
[1] 0.05436957 0.10484454

I would like to save the first and second elements of each diagonal of a given list into a vector similar to this:

d.1st.el <- c(0.04770856, 0.05436957)
d.2nd.el <- c(0.03260190, 0.10484454)

My issue is to write the function that runs for all given lists and get the diagonals. For some reason, when I use unlist() to extract the values of each matrix for a given level, it doesn't get me the number but the full matrix.

Does anyone have a simple solution?


Solution

  • sapply(res, diag)
    
               [,1]       [,2]
    [1,] 0.04770856 0.05436957
    [2,] 0.03260190 0.10484454
    
    # or
    lapply(res, diag)
    [[1]]
    [1] 0.04770856 0.03260190
    
    [[2]]
    [1] 0.05436957 0.10484454
    

    If you want the vectors for some reason in your global environment:

    alld <- lapply(res, diag)
    names(alld) <- sprintf("d.%d.el", 1:length(alld))
    list2env(alld, globalenv())