1

I have a matrix that I would like to subset. When I subset it the output I want is the value of its rowname.

m
  x y
A 2 2
B 2 2
C 1 3
D 1 1
E 1 2

m2
  x y
1 1 2

This is what I currently have, which is clearly not the right output. This seems straightforward, but I've yet to have it figured out.

which(m2==m, arr.ind=TRUE)
  row col
1   1   2

The output should be

output
"E"

m2 can have more than 1 line to subset m with.

user3067923
  • 437
  • 2
  • 14

1 Answers1

1

If you make every column of m2 a vector, you could borrow the technique shown in this answer. Notice, I added an additional row to m2 to better illustrate the problem:

m <- matrix(c(2,2,2,2,1,3,1,1,1,2), 
            nrow = 5, ncol = 2, byrow = T, 
            dimnames = list(LETTERS[1:5], c("x", "y")))

m2 <- matrix(c(1,2,2,2), nrow = 2, ncol = 2, byrow = T, 
             dimnames = list(c(1,2), c("row", "col")))

apply(m2, 1, function(i) rownames(m)[colSums(t(m) == as.vector(i)) == ncol(m)])

# $`1`
# [1] "E"
# 
# $`2`
# [1] "A" "B"

The shorter, De Morgan's Law version suggested in this answer would also apply...

apply(m2, 1, function(i) rownames(m)[!colSums(t(m) != as.vector(i))])
Community
  • 1
  • 1
JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116