jferrer
jferrer

Reputation: 33

Select a column from a list of matrices using a list of vectors

I want to select columns from a list of matrices of different dimension using a list of Boolean vectors that represent the columns of each matrix.

I have tried different map and (s|l)apply combinations, even classic for loops, but I can't manage to select the columns.

With this code, you can generate a list of matrices and Boolean vectors to experiment:

matrices <- list(matrix(c(7,8,9,10), nrow=1), matrix(c(7,8,7,9,7,10,8,9,8,10,9,10), nrow=2), matrix(c(7,8,9,7,8,10,7,9,10,8,9,10), nrow=3))
listOfColumns <- list(c(FALSE,FALSE,FALSE,FALSE), c(FALSE,FALSE,FALSE,FALSE,FALSE,FALSE), c(TRUE,FALSE,FALSE,FALSE))

As an example, having the list of matrices created with the above code:

[[1]]
     [,1] [,2] [,3] [,4]
[1,]    7    8    9   10

[[2]]
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    7    7    7    8    8    9
[2,]    8    9   10    9   10   10

[[3]]
     [,1] [,2] [,3] [,4]
[1,]    7    7    7    8
[2,]    8    8    9    9
[3,]    9   10   10   10

and the list of Boolean vectors:

[[1]]
[1] FALSE FALSE FALSE FALSE

[[2]]
[1] FALSE FALSE FALSE FALSE FALSE FALSE

[[3]]
[1]  TRUE FALSE FALSE FALSE

The result should be a list with a single element:

[[1]]
[1] 7 8 9

Upvotes: 2

Views: 201

Answers (1)

markus
markus

Reputation: 26333

Because your list contains matrices that you don't want to keep at all we can first create an index vector that selects only list elements of listOfColumns for which there is at least one TRUE

(idx <- sapply(listOfColumns, any))
# [1] FALSE FALSE  TRUE

Next we use Map to subset the remaining matrices

Map(function(x, cols) x[, cols], x = matrices[idx], cols = listOfColumns[idx])
#[[1]]
#[1] 7 8 9

Thanks to @thelatemail for the helpful comment.

Upvotes: 1

Related Questions