[R] avoid a loop

cory n corynissen at gmail.com
Thu Nov 4 20:42:08 CET 2010


Let's suppose I have userids and associated attributes...  columns a and b

a <- c(1,1,1,2,2,3,3,3,3)
b <- c("a","b","c","a","d","a", "b", "e", "f")

so a unique list of a would be

id <- unique(a)

I want a matrix like this...

     [,1] [,2] [,3]
[1,]    3    1    2
[2,]    1    2    1
[3,]    2    1    4

Where element i,j is the number of items in b that id[i] and id[j] share...

So for example, in element [1,3] of the result matrix, I want to see
2.  That is, id's 1 and 3 share two common elements in b, namely "a"
and "b".

This is hard to articulate, so sorry for the terrible description
here.  The way I have solved it is to do a double loop, looping over
every member of the id column and comparing it to every other member
of id to see how many elements of b they share.  This takes forever.

Thanks

cn



More information about the R-help mailing list