[R] Match numeric vector against rows in a matrix?

William Dunlap wdunlap at tibco.com
Fri Jan 7 18:38:53 CET 2011


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Petr Savicky
> Sent: Friday, January 07, 2011 2:11 AM
> To: r-help at r-project.org
> Subject: Re: [R] Match numeric vector against rows in a matrix?
> 
> On Wed, Jan 05, 2011 at 07:16:47PM +0000, 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)
> > 
> > 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.
> 
> If the matrix can have different number of columns, then
> also the following can be used
> 
>   combs <- as.matrix(expand.grid(c(0,1),c(0,1),c(0,1)))
>   x <- c(0,1,1)
>   which(rowSums(combs != rep(x, each=nrow(combs))) == 0) # [1] 7

If the combs matrix always has that form, why not
dispense with it and treat x as the binary expansion
of the row number (+1)?
   > 1 + sum( 2^(seq_along(x)-1) * x )
   [1] 7

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 
 
> Petr Savicky.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 



More information about the R-help mailing list