Home > Software design >  Indexing the columns of matrices in a list by another list
Indexing the columns of matrices in a list by another list

Time:09-09

Suppose I have a list containing two matrices with different dimensions.

a <- matrix(rnorm(n=12), nrow = 3, ncol=4)
b <- matrix(rnorm(n=12), nrow = 4, ncol=3)
list1 <- list(a, b)

list1

#[[1]]
#           [,1]       [,2]      [,3]      [,4]
#[1,] -1.4654114  2.1251278 2.5363265 0.3127435
#[2,]  0.5701815 -1.0877491 0.6314599 1.5293045
#[3,]  2.0811299  0.3109243 0.2300760 0.5495488
#
#[[2]]
#          [,1]      [,2]     [,3]
#[1,] 0.9082071 1.7337076 2.207299
#[2,] 2.1287871 1.6839454 1.527546
#[3,] 0.8175804 0.8086223 1.165589
#[4,] 0.7410989 0.8237012 1.729501

Additionally, I have a list containing two vectors.

a2 <- c("yes", "no", "yes", "yes")
b2 <- c("no", "yes", "no")
list2 <- list(a2, b2)

list2

#[[1]]
#[1] "yes" "no"  "yes" "yes"
#
#[[2]]
#[1] "no"  "yes" "no" 

How can I index to only the columns in list1 that correspond to where list2 says "yes"?

In other words, can I index the columns of each matrix in list1 by the character values in list2?

CodePudding user response:

Map the values together, and select the columns:

set.seed(1)
# run the rnorm/matrix code in the question to make it reproducible with this seed
Map(\(on,tw) on[, tw=="yes", drop=FALSE], list1, list2)
#[[1]]
#           [,1]      [,2]       [,3]
#[1,] -0.6264538 0.4874291 -0.3053884
#[2,]  0.1836433 0.7383247  1.5117812
#[3,] -0.8356286 0.5757814  0.3898432
#
#[[2]]
#            [,1]
#[1,] -0.01619026
#[2,]  0.94383621
#[3,]  0.82122120
#[4,]  0.59390132
  •  Tags:  
  • r
  • Related