title: How to create a co-occurrence matrix of elements that co-occur in a row in R?
body: <p>I'm a rookie in R and I want to create a co-occurrence matrix based on which elements co-occur in a row.</p>
  <p><strong>Basic Example of Aspired Outcome</strong></p>
  <p>Say you have this table:</p>
  <pre><code>df &lt;- data.frame(ID = c(1,2,3), 
                   V1 = c(&quot;England&quot;, &quot;England&quot;, &quot;China&quot;),
                   V2 = c(&quot;Greece&quot;, &quot;England&quot;, &quot;Greece&quot;)
  )
  </code></pre>
  <p>That is:</p>
  <pre><code>   ID      V1      V2
  1:  1 England  Greece
  2:  2 England England
  3:  3   China  Greece
  </code></pre>
  <p>My co-occurrence matrix should look like this:</p>
  <pre><code>Country   China    England  Greece
  China           0       0      1 #China &amp; Greece co-occur in row 3
  England         0       1      1 #England &amp; England co-occur in row 2, and England and Greece in row 1
  Greece          1       1      0 
  </code></pre>
  <p>However, if I follow this <a href="https://stackoverflow.com/a/59636519/3432632">example</a> I get this:</p>
  <pre><code>library(tidyverse)
  df %&gt;%
        pivot_longer(-ID, names_to = &quot;Category&quot;, values_to = &quot;Country&quot;) %&gt;%
        xtabs(~ID + Country, data = ., sparse = FALSE) %&gt;% 
        crossprod(., .) 
      
      df_diag &lt;- df %&gt;% 
        pivot_longer(-ID, names_to = &quot;Category&quot;, values_to = &quot;Country&quot;) %&gt;%
        mutate(Country2 = Country) %&gt;%
        xtabs(~Country + Country2, data = ., sparse = FALSE) %&gt;% 
        diag()
      
      diag(df1) &lt;- df_diag 
      
      df1
  
  Country   China England Greece
    China       1       0      1
    England     0       3      1
    Greece      1       1      2
  </code></pre>
  <p>And if I follow this other <a href="https://stackoverflow.com/a/59666796/3432632">one</a> I get:</p>
  <pre><code>library(reshape2)
  library(data.table)
  
  melt(setDT(df), id.vars = &quot;ID&quot;, measure = patterns(&quot;^V&quot;))[nchar(value) &gt; 0 &amp; complete.cases(value)] -&gt; foo
  
  # Get distinct value (country) in each ID group (each row)
  unique(foo, by = c(&quot;ID&quot;, &quot;value&quot;)) -&gt; foo2
  
  # https://stackoverflow.com/questions/13281303/creating-co-occurrence-matrix
  # Seeing this question, you want to create a matrix with crossprod().
  
  crossprod(table(foo2[, c(1,3)])) -&gt; mymat
  
  # Finally, you need to change diagonal values. If a value is equal to one,
  # change it to zero. Otherwise, keep the original value.
  
  diag(mymat) &lt;- ifelse(diag(mymat) &lt;= 1, 0, mymat)
  
  mymat
  
  value     China England Greece
    China       0       0      1
    England     0       0      1
    Greece      1       1      1
  </code></pre>
  <p>I guess I'm missing something about how xtabs works or perhaps also crosspod?</p>