简体   繁体   English

r将逻辑矩阵列表应用于矩阵列表

[英]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"). 我想应用此逻辑矩阵列表来获取带有下三角(“ TRUE”)值的向量列表。

I've tried multiple ways, eg 我尝试了多种方法,例如

my_list[lowtri]

But I haven't been able to figure out how to do this. 但是我还无法弄清楚该怎么做。

We can use Map to extract the values of each of the matrix based on the corresponding logical matrix in 'lowtri' list 我们可以使用Map根据“ lowtri” list相应的逻辑matrix提取每个matrix的值

Map(`[`, my_list, lowtri)

Or using map2 from purrr 或使用purrr map2

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

考虑绕过生成逻辑矩阵,然后在列表中应用lower.tri()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM