[R] pairs

Linlin Yan yanlinlin82 at gmail.com
Mon Nov 16 01:23:08 CET 2009


Hope this help:

> m <- matrix(c(2,1,3,9,5,7,7,8,1,8,6,5,6,2,2,7),4,4)
> p <- c(2, 6)

> apply(m == p[1], 1, any) & apply(m == p[2], 1, any)
[1]  TRUE FALSE  TRUE FALSE

If you want the number of rows which contain the pair, sum() could be used:

> sum(apply(m == p[1], 1, any) & apply(m == p[2], 1, any))
[1] 2

On Mon, Nov 16, 2009 at 6:26 AM, cindy Guo <cindy.guo3 at gmail.com> wrote:
> Hi, All,
>
> I have an n by m matrix with each entry between 1 and 15000. I want to know
> the frequency of each pair in 1:15000 that occur together in rows. So for
> example, if the matrix is
> 2 5 1 6
> 1 7 8 2
> 3 7 6 2
> 9 8 5 7
> Pair (2,6) (un-ordered) occurs together in rows 1 and 3. I want to return
> the value 2 for this pair as well as that for all pairs. Is there a fast way
> to do this avoiding loops? Loops take too long.
>
> Thank you,
>
> Cindy
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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