Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think I managed to do it with this single disgusting line:</p> <pre><code>cast(aggregate(value ~ X1 + X2, rbind(melt(M1), melt(M2)), sum), X1 ~ X2)[,-1] </code></pre> <p>This makes use of the <code>reshape</code> package. Returned as a data frame so convert to matrix as necessary.</p> <p>If you want it in the format you suggested in your example, try this:</p> <pre><code>"%ms%" &lt;- function(m1, m2) { m &lt;- as.matrix(cast(aggregate(value ~ X1 + X2, rbind(melt(m1), melt(m2)), sum), X1 ~ X2)[,-1]) mn &lt;- unique(colnames(m1), colnames(m2)) rownames(m) &lt;- mn colnames(m) &lt;- mn return (m) } </code></pre> <p>Then you can do:</p> <pre><code>M1 %ms% M2 </code></pre> <p><hr /> EDIT:</p> <h2>EXPLANATION</h2> <p>Obviously should have some explanation sorry.</p> <pre><code>melt(M1) </code></pre> <p>Converts <code>M1</code> from its original form into a format like this (row, col, value). E.g.</p> <pre><code> 1 3 4 5 7 8 1 0 0 1 0 0 0 3 0 0 0 0 0 0 4 1 0 0 0 0 0 5 0 0 0 0 0 0 7 0 0 0 0 1 0 8 0 0 0 0 0 0 </code></pre> <p>Is converted to:</p> <pre><code> X1 X2 value 1 1 1 0 2 3 1 0 3 4 1 1 </code></pre> <p>etc. Combining <code>M1</code> and <code>M2</code> lists every possible (row, col, value) across both matrix into one single matrix. Now this:</p> <pre><code>aggregate(value ~ X1 + X2, rbind(melt(M1), melt(M2)), sum) </code></pre> <p>Sums values where the row and column are the same. So it will sum (1, 1) across both matrices for example. And (3, 1) etc. It won't do anything that doesn't exist e.g. <code>M2</code> doesn't have a 7th column/row.</p> <p>Finally <code>cast</code> transforms the matrix so that it is written with the result of <code>aggregate</code>'s first column as rows, its second column as columns. Effectively undoing the melt from earlier. The <code>[,-1]</code> is taking off an unnecessary column leftover from <code>cast</code> (I think there is probably a better way of doing that but I don't know how).</p> <p>As I said, it's returned as a data frame so use <code>as.matrix()</code> on the result if that's what you wish.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload