Neuroguy
Neuroguy

Reputation: 141

r apply a list of logical matrices to a list of matrices

I have a list of symmetrical matrices that I want to use only the lower triangle for:

my_list

$m1
     V1   V2   V3   V4   V5
[1,] 1.00 0.22 0.27 0.30 0.35
[2,] 0.22 1.00 0.33 0.35 0.15
[3,] 0.27 0.33 1.00 0.44 0.44
[4,] 0.30 0.35 0.44 1.00 0.44
[5,] 0.35 0.15 0.44 0.44 1.00

$m2
     V1   V2   V3   V4   V5
[1,] 1.00 0.16 0.34 0.26 0.23
[2,] 0.16 1.00 0.33 0.20 0.21
[3,] 0.34 0.33 1.00 0.34 0.44
[4,] 0.26 0.20 0.34 1.00 0.18
[5,] 0.23 0.21 0.44 0.18 1.00`

To get the lower triangle, I first made a list of logical matrixes using

lowtri <- lapply(DATA_RSAbrain,lower.tri)

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

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

I want to apply this list of logical matrices to get a list of vectors with values from the lower triangle (the "TRUEs").

I've tried multiple ways, e.g.

my_list[lowtri]

But I haven't been able to figure out how to do this.

Upvotes: 1

Views: 106

Answers (2)

Parfait
Parfait

Reputation: 107577

Consider bypassing generating the logical matrices, and apply lower.tri() on your list:

new_list <- lapply(my_list, function(x) x[lower.tri(x)])

Upvotes: 2

akrun
akrun

Reputation: 887078

We can use Map to extract the values of each of the matrix based on the corresponding logical matrix in 'lowtri' list

Map(`[`, my_list, lowtri)

Or using map2 from purrr

library(tidyverse)
map2(my_list, lowtri, `[`)

Upvotes: 2

Related Questions