 <p>Looking at your desired output, you are looking for the <code>crossprod</code> function:</p> <pre><code>crossprod(table(test1)) # product # product p1 p2 p3 p4 # p1 4 1 1 0 # p2 1 3 1 0 # p3 1 1 4 1 # p4 0 0 1 2 </code></pre> <p>This is the same as <code>crossprod(table(test1$user, test1$product))</code> (reflecting Dennis's comment).</p>