# How to find similarity in R or Python? [closed]

I have a data set as I've shown below:

It shows which book is sold by which shop. Also, every book_id has a type.

df <- tribble(
~shop,  ~book_id,  ~type,
"A",       1,      'X',
"B",       1,      'X',
"C",       2,      'Y',
"D",       3,      'Z',
"E",       3,      'Z',
"A",       3,      'Z',
"B",       4,      'X',
"C",       5,      'Y',
"D",       1,      'X',
)


In the data set,

• shop A sells 1, 3
• shop B sells 1, 4
• shop C sells 2, 5
• shop D sells 3, 1
• shop E sells only 3

I want to see the similarity among shops based on the book_id. In other words, I want to see the intersection/overlapping among the shops.

First, I thought it is a manipulation problem. But it seems that I should need more than manipulation to get my desired data that I've shown below:

df <- tribble(
~shop_1, ~shop_2, ~similarity,
'A',      'B',       '?',
'A',      'C',       '?',
'A',      'D',       '?',
'A',      'E',       '?',
'B',      'C',       '?',
'B',      'D',       '?',
'B',      'E',       '?',
'C',      'D',       '?',
'C',      'E',       '?',
'D',      'E',       '?',
)


Any comments/assistance really appreciated! Thanks in advance.

Note: Question mark (?) in similarity column in the desired data was used because I don't how to calculate the similarity.

For comparison, you should create a contingency matrix with table(df$shop, df$book_id) (but you may want to use a tool like xtabs instead, to create a sparse matrix from package Matrix). Then, you can compute similarities between rows of that matrix (every row is a shop).

A suitable, notorious similarity measure is Jaccard index, but many more exist. Anyway, I see an R package exists for Jaccard measure alone, fittingly called jaccard.