Re: [R] Vector comparison to matrix

From: Ravi Varadhan <rvaradha_at_jhsph.edu>
Date: Mon 15 Aug 2005 - 23:49:09 EST


Hi Todd,

Here is a function that was suggested to me by Gabor Grothendieck. This function counts the number of times each row of a matrix B occurs in another matrix A.

rowmatch.count <- function(a,b) {

    f <- function(...) paste(..., sep=":")
    a2 <- do.call("f", as.data.frame(a))
    b2 <- do.call("f", as.data.frame(b))
    c(table(c(a2,unique(b2)))[b2] - 1)
}

If you are interested in finding the number of occurrences of a vector "b" instead, you can call this function as follows:

rowmatch.count(A,t(as.matrix(b))

Hope this is helps,
Ravi.

> -----Original Message-----
> From: r-help-bounces@stat.math.ethz.ch [mailto:r-help-
> bounces@stat.math.ethz.ch] On Behalf Of Todd Remund
> Sent: Monday, August 15, 2005 1:13 AM
> To: r-help@stat.math.ethz.ch
> Subject: [R] Vector comparison to matrix
>
> I am looking for a fast way to count the number of rows in a matrix are
> identical to a pattern vector. For example, if I am interested in
> counting
> the number of row vectors in a matrix that are identical to (1,2,3) what
> would I do? I have tried the identical statement in a loop but this is
> far
> too slow. I have a very large matrix and need to avoid loops at all
> costs.
> Thanks for any help.
> Todd Remund
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-
> guide.html



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Mon Aug 15 23:55:02 2005

This archive was generated by hypermail 2.1.8 : Sun 23 Oct 2005 - 15:19:56 EST