[R] Match numeric vector against rows in a matrix?
David Winsemius
dwinsemius at comcast.net
Wed Jan 5 23:16:54 CET 2011
On Jan 5, 2011, at 2:16 PM, Kevin Ummel wrote:
> Two posts in one day is not a good day...and this question seems
> like it should have an obvious answer:
>
> I have a matrix where rows are unique combinations of 1's and 0's:
>
>> combs=as.matrix(expand.grid(c(0,1),c(0,1)))
>> combs
> Var1 Var2
> [1,] 0 0
> [2,] 1 0
> [3,] 0 1
> [4,] 1 1
>
> I want a single function that will give the row index containing an
> exact match with vector x:
>
>> x=c(0,1)
> intersect( which(combs[,1]==x[1]), which(combs[,2]==x[2]) )
[1] 3
Or maybe even faster:
> which( combs[,1]==x[1] & combs[,2]==x[2])
[1] 3
>
> The solution needs to be applied many times, so I need something
> quick -- I was hoping a base function would do it, but I'm drawing a
> blank.
>
--
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list