Reputation: 457
I have a matrix I would like to subset quickly using two criteria. 1) the colnames match the rownames and 2) the value in one matrix is FALSE
m
[,1]
A 1
B 2
C 3
D 4
E 5
tf
E B A
[1,] FALSE FALSE TRUE
the output should be
m2
[,1]
E 5
B 2
Upvotes: 1
Views: 62
Reputation: 887501
As there is only a single row for 'tf', when we subset the logical matrix by negating, it results in a named vector
as subsetting ([
) by default is drop=TRUE
. Extract the names
from the vector
and use it as row index to subset the 'm'. Here, we can use drop=FALSE
as there is only a single column in 'm'.
m[names(tf[,!tf]), , drop=FALSE]
# [,1]
#E 5
#B 2
m <- matrix(1:5, nrow=5, 1, dimnames=list(LETTERS[1:5], NULL))
tf <- matrix(c(FALSE, FALSE, TRUE), ncol=3, dimnames=list(NULL, c("E", "B", "A")))
Upvotes: 2