title: Turn matrix into a paired list using apply in R?
body: <p>I have a matrix similar to the one below but larger.</p>
  
  <pre><code>vec &lt;- c(0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0)
  M &lt;- matrix(vec, nrow = 4, byrow = TRUE)
  colnames(M) &lt;- rownames(M) &lt;- LETTERS[1:4]
  
     A, B, C, D
  A, 0, 1, 1, 0
  B, 0, 0, 1, 1
  C, 1, 0, 0, 0
  D, 0, 1, 1, 0
  </code></pre>
  
  <p>Ultimately, I would like a matrix or a data.frame where each time a call in a row has a value, I end up with a rowname,column name pair. So, given the above matrix, I end up with the matrix or data frame below:</p>
  
  <pre><code>A,B
  A,C
  B,C
  B,D
  C,A
  D,B
  D,C
  </code></pre>
  
  <p>I can do this with loops and with expand.grid, but this seems like something I should be able to do with the apply functions. For example, I can get part way there like this:</p>
  
  <pre><code>tmp &lt;- apply(M, 1, function(x) colnames(M)[which(x &gt; 0)])
  </code></pre>
  
  <p>which gives me</p>
  
  <pre><code>$A
  [1] "B" "C"
  $B
  [1] "C" "D"
  $C
  [1] "A"
  $D
  [1] "B" "C"
  </code></pre>
  
  <p>If that is easy, then can I also include the number in the cell (for cells over 0) as a third column?</p>