Vectorisation of for loop with multiple conditions : <pre><code>dummies  = matrix(c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0), nrow=6, ncol=6) 
colnames(dummies)  &lt;- c("a","b", "c", "d", "e", "f")
</code></pre>

<p>I have a matrix with dummies</p>

<pre><code>&gt; dummies
     a b c d e f
[1,] 0 0 0 0 1 0
[2,] 0 0 1 0 0 0
[3,] 1 0 0 0 0 0
[4,] 0 0 0 0 0 1
[5,] 0 1 0 0 0 0
[6,] 0 0 0 1 0 0
</code></pre>

<p>I know that my dummies are related in that line 1 is grouped with 2, 3 with 4, and 5 with 6. I want to split each dummy code(1) between those in the same group on the same line as above:</p>

<pre><code>&gt; dummies
        a    b    c    d    e    f
[1,]  0.0  0.0 -0.5  0.0  0.5  0.0
[2,]  0.0  0.0  0.5  0.0 -0.5  0.0
[3,]  0.5  0.0  0.0  0.0  0.0 -0.5
[4,] -0.5  0.0  0.0  0.0  0.0  0.5
[5,]  0.0  0.5  0.0 -0.5  0.0  0.0
[6,]  0.0 -0.5  0.0  0.5  0.0  0.0 
</code></pre>

<p>To achieve this, I do the following:</p>

<pre><code>dummies &lt;- ifelse(dummies==1, 0.5, 0)
for (i in 1:nrow(dummies)){
    column = which(dummies[i,] %in% 0.5)
    if (i %% 2 != 0) {      
      dummies[i+1, column] &lt;- -0.5
    } else {            
      dummies[i-1, column] &lt;- -0.5
   }
 }
</code></pre>

<p>My question is whether I could achieve this with vectorised code. I cannot figure out how to use <code>ifelse</code> in this case because I cannot combine it with the line indexing to find the <code>0.5</code> on each line. </p>
