title: Pairwise interaction matrix in R
body: <p>I am trying to compute a pairwise matrix in R that counts the number of times individuals interact with other individuals (so the matrix will include N number of rows and columns corresponding to number of individuals). I have a dataframe that lists "actors" and "partners" in separate columns.</p>
  
  <pre class="lang-r prettyprint-override"><code>nn &lt;- data.frame(actors=c('DOL','DOL','DOL','DOL','DOL','NOR','NOR','NOR','NIN','JOJ'),partners=c('JOJ','JOJ','NOR','NOR','NIN','NIN','DOL','JOJ','NOR','NOR'))
  </code></pre>
  
  <p>The data are such that direction of the interaction is irrelevant, so each cell should count the number of times individual X acts on Y plus the number of times Y acts on X. Ideally, the data frame above should give a matrix that looks like this:
  </p>
  
  <pre><code>     DOL JOJ NOR NIN
  DOL    0   2   3   1
  JOJ    2   0   2   0
  NOR    3   2   0   2
  NIN    1   0   2   0
  </code></pre>
  
  <p>I started writing a loop to cycle through each individual in my dataset and to count his/her interactions both from actor->partner and partner->actor. I'm sure this would work, but is not ideal as the full dataset is quite large. Is there a better way?</p>
  
  <hr>
  
  <p>Update:
  Thanks for the responses! Both solutions work great! I'm posting my implementation of Josh's suggestion, which was very helpful.</p>
  
  <pre><code>x &lt;- with(nn, table(actors, partners))
  y &lt;- t(x)
  
  # unique individuals
  u &lt;- unique(c(rownames(x),colnames(x)))
  
  m &lt;- matrix(0,ncol=length(u),nrow=length(u),dimnames=list(u,u))
  
  i1 &lt;- as.matrix(expand.grid(rownames(x),colnames(x)))
  i2 &lt;- as.matrix(expand.grid(rownames(y),colnames(y)))
  
  m[i1] &lt;- x[i1]
  m[i2] &lt;- m[i2] + y[i2]
  </code></pre>