Robin
Robin

Reputation: 459

How to return the index of the matching row when comparing a matrix to a vector in r

The data are:

a <- matrix(c(1,1,2,2,'a','b','c','d'),4,2)
b <- c(1,'a')

So the first row of a matches b. If I want to return the index of the row in the matrix a (which is 1), what code would I apply in r? I tried:

which((a[,1]==b[1])&(a[,2]==b[2])), is there any other option?

Upvotes: 4

Views: 923

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 388982

Couple of more options :

which(colSums(t(a) != b) == 0)

and

which(rowSums(sweep(a, 2, b, `!=`)) == 0)

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101538

Another option but with match

match(list(b),asplit(a,1))

or

match(asplit(t(b),1),asplit(a,1))

or

match(as.data.frame(t(t(b))),as.data.frame(t(a)))

Upvotes: 3

akrun
akrun

Reputation: 887148

We can replicate the 'b' by the row of 'a' and do an elementwise comparison, then wrap the which to get the index

which(a == b[row(a)])

Note that this gives the index of the element. If we need the index of row where everything matches.

which(rowSums(a == b[col(a)]) == ncol(a))

Or

 which(a == b)

Upvotes: 3

Related Questions