'How would I count matches?

I have a list of IDs and location like this:

id <- c('i1','i2','i3','i1','i2','i3')
location <- c('x','x','y','y','z','z')
example <- data.frame(location,id)

What I'd like to do is count the number of times IDs occur in the same location, potentially ending with something similar to this:

i1 <- c(2,1,1)
i2 <- c(1,2,1)
i3 <- c(1,1,2)
finish <- data.frame(i1,i2,i3, row.names = c('i1','i2','i3'))

So what's happening is me ending with a chart identifying which IDs share locations.

r


Solution 1:[1]

We may use table with crossprod

crossprod(table(example))
  id
id   i1 i2 i3
  i1  2  1  1
  i2  1  2  1
  i3  1  1  2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 akrun