title: Quicker way of transforming matrices in r?
body: <p>I am trying to transform a matrix according to various rules.</p>
  
  <p>Take this matrix, m:</p>
  
  <pre><code>x&lt;-c(NA,0,0,0,0,0,4,NA,0,0,1,1,0,0,NA,0,2,4,4,1,3,NA,2,3,0,1,2,0,NA,1,0,0,0,0,0,NA)
  m&lt;-matrix(x,6,6, byrow=T)
  rownames(m)&lt;-colnames(m)&lt;-LETTERS[1:6]
  m
  
  #   A  B  C  D  E  F
  #A NA  0  0  0  0  0
  #B  4 NA  0  0  1  1
  #C  0  0 NA  0  2  4
  #D  4  1  3 NA  2  3
  #E  0  1  2  0 NA  1
  #F  0  0  0  0  0 NA
  </code></pre>
  
  <p>The rules for transforming it are as follows:</p>
  
  <p>1) The diagonal should remain NA.</p>
  
  <p>2) For all instances where m[i,j]>m[j,i]  then m[i,j] gets a '1' and m[j,i] gets a 0.</p>
  
  <p>3) For all instances where m[i,j]==m[j,i]  AND both are NOT EQUAL to 0, then m[i,j] and m[j,i] should both get assigned 0.5</p>
  
  <p>4) When m[i,j] and m[j,i] both are equal to 0, then one of them should randomly get a '1' and the other should get a '0'.</p>
  
  <p>I can do steps 1-3 with this calculation:</p>
  
  <pre><code> m1 &lt;- (m &gt; t(m))+0 + (((m == t(m)) &amp; (m!=0 &amp; t(m)!=0)) + 0)/2
   m1
  </code></pre>
  
  <p>which gives:</p>
  
  <pre><code>#   A   B   C  D   E  F
  #A NA 0.0 0.0  0 0.0  0
  #B  1  NA 0.0  0 0.5  1
  #C  0 0.0  NA  0 0.5  1
  #D  1 1.0 1.0 NA 1.0  1
  #E  0 0.5 0.5  0  NA  1
  #F  0 0.0 0.0  0 0.0 NA
  </code></pre>
  
  <p>Now I need to do step 4.  The instances where m1[i,j] and m1[j,i] are both equal to 0 in this matrix can be found with:</p>
  
  <pre><code>(m1==0 &amp; t(m1)==0)
  
     #       A     B     C     D     E     F
     # A    NA FALSE  TRUE FALSE  TRUE  TRUE
     # B FALSE    NA  TRUE FALSE FALSE FALSE
     # C  TRUE  TRUE    NA FALSE FALSE FALSE
     # D FALSE FALSE FALSE    NA FALSE FALSE
     # E  TRUE FALSE FALSE FALSE    NA FALSE
     # F  TRUE FALSE FALSE FALSE FALSE    NA
  </code></pre>
  
  <p>which shows that the instances are AC/CA, AE/EA, AF/FA, BC/CB.</p>
  
  <p>An example of the output I am looking for :</p>
  
  <pre><code>#   A   B   C  D   E  F
  #A NA 0.0 1.0  0 0.0  0
  #B  1  NA 1.0  0 0.5  1
  #C  0 0.0  NA  0 0.5  1
  #D  1 1.0 1.0 NA 1.0  1
  #E  1 0.5 0.5  0  NA  1
  #F  1 0.0 0.0  0 0.0 NA
  </code></pre>
  
  <p>I know that it's possible to assign to both the upper and lower triangle the same values, e.g. NA in this code:     <code>m1[((m1==0 &amp; t(m1)==0))] &lt;- NA</code>   , but not sure how that is relevant here.   I could also melt the matrix into a pairwise list and do a long winded solution - but the purpose of this is to run thousands of simulations and so speed is very, very important.</p>
  
  <p>Any guidance appreciated.</p>