Skip to content
Prev 257873 / 398502 Next

Matching a vector with a matrix row

I gave a solution previously with integer elements.  It also works well for real numbers.

rowMatch <- function(A,B) {
# Rows in A that match the rows in B
# The row indexes correspond to A
    f <- function(...) paste(..., sep=":")
   if(!is.matrix(B)) B <- matrix(B, 1, length(B))
    a <- do.call("f", as.data.frame(A))
    b <- do.call("f", as.data.frame(B))
    match(b, a)
}

A <- matrix(rnorm(100000), 5000, 20)
sel <- sample(1:nrow(A), size=100, replace=TRUE)
B <- A[sel,]

system.time(rows <- rowMatch(A, B ))
all.equal(sel, rows)

sel <- sample(1:nrow(A), size=1)
b <- c(A[sel,])
system.time(row <- rowMatch(A, b))
all.equal(sel, row)

I am curious to see if there are better/faster ways to do this.

Ravi.