title: Can I avoid a triple for-loop with an if statement in R?
body: <p>I have an O = n x m matrix containing 0s and 1s that I have to transform into m matrices of M_j = n x n dimension. Each of those M_j matrices will have value 1 if:
  element i of column j of the O matrix is equal to 1 &amp; element k of column j of the O matrix is equal to 0;
  and will have value 0 otherwise.
  I've managed to create a script using a triple for-loop and an if statement in R that does this quite easily, but I'm sure there must be a much more efficient way to do this. However, I can't really think of how to vectorize/use sapply/ something else.
  Any suggestions?</p>
  <p>My sample code:</p>
  <pre><code>o &lt;- data.frame(s1 = c(1,0,0),
                  s2 = c(0,1,1),
                  s3 = c(1,0,1),
                  s4 = c(0,1,1))
  
  
  #### MATRICES M (4 matrices of 3x3) ----
  m &lt;- list()
  n_ocup &lt;- nrow(o)
  n_skill &lt;- ncol(o)
  
  for (i in 1:n_skill){
    
    print(paste0(&quot;########### M&quot;, i, &quot; ###########&quot;))
    temp_m &lt;- matrix(nrow = n_ocup, ncol = n_ocup, 0)
    temp_o &lt;- o[,i]
    
    for (j in 1:nrow(temp_m)){
      for (k in 1:ncol(temp_m)){
        
        if (temp_o[j,1]==1 &amp; temp_o[k,1]==0){
          temp_m[k,j] &lt;- 1 #seems backwards but it's OK
        }
      }
    }
  
    m[[i]] &lt;- temp_m
    
  }
  </code></pre>
  <p>Thank you very much in advance!!</p>