[R] Counting number of common elements between the rows of two different matrices

Parodi, Pietro Pietro.Parodi at willis.com
Fri Nov 4 13:51:58 CET 2011


I'm trying to solve this problem without using a for loop but I have so
far failed to find a solution.

I have two matrices of K columns each, e.g. (K=5), and with numbers of
row N_A and N_B respectively

A = 	(1 5 3 8 15;
	 2 7 20 11 13;
	 12 19 20 21 43)

B = 	(2 6 30 8 16;
	 3 8 19 11 13)

(the actual matrices have hundreds of thousands of entry, that's why I'm
keen to avoid "for" loops)

And what I need to do is to apply a function which counts the number of
common elements between ANY row of A and ANY row of B, giving a result
like this:

A1 vs B1:  1  # (8 is a common element)
A1 vs B2:  1  # (8 is a common element)
A2 vs B1:  1  # (2 is a common element)
A2 vs B2:  1  # 11, 13 are common elements

I've built a function that counts the number of common elements between
two vectors, based on the intersect function in the R manual

common_elements <- function(x,y) length(y[match(x,y,nomatch=0)])

And a double loop who solves my problem would be something like

For(i in 1:N_A){
	for(j in 1:N_B){

Is there an efficient, clean way to do the same job and give as an
output a matrix N_A x N_B such as that above?

Thanks a lot for your help




For information pertaining to Willis' email confidentiality and monitoring policy, usage restrictions, or for specific company registration and regulatory status information, please visit http://www.willis.com/email_trailer.aspx

We are now able to offer our clients an encrypted email capability for secure communication purposes. If you wish to take advantage of this service or learn more about it, please let me know or contact your Client Advocate for full details. ~W67897

More information about the R-help mailing list