Add new variable with for loop and if statements in R
<p>Let's assume I have a data set with 2 variables, a and b, where all b's are a's, but not all a's are b's. </p>

<pre><code>a&lt;-rbind(1,1,1,1,1)
b&lt;-rbind(0,0,0,1,1)
d&lt;-cbind(a,b)
d
      [,1] [,2]
[1,]    1    0
[2,]    1    0
[3,]    1    0
[4,]    1    1
[5,]    1    1
</code></pre>

<p>I want to create a new third variable to condense this information into a single data frame. I attempted to do so by writing a loop for 1 in nrows, if the a variable is 1 then write a 2, and if the b variable is 1 then write a 1</p>

<pre><code>e&lt;- for (i in 1:nrow(d)) {
    if (d[,1]==1) {
        e$new[,i] &lt;- 2
    } # end if 1
    else (d[,2]==1)
    e$new[,i]&lt;-1
        } # end for 2

} # end for
</code></pre>

<p>I basically want the output to look as such:</p>

<pre><code>&gt; d
       [,1] [,2] [,3]
 [1,]    1    0    2
 [2,]    1    0    2
 [3,]    1    0    2
 [4,]    1    1    1
 [5,]    1    1    1
</code></pre>

<p>I keep getting an error: Error in e$new[, i] &lt;- 0 : incorrect number of subscripts on matrix
In addition: Warning messages:
1: In 1:x : numerical expression has 2 elements: only the first used
2: In if (d[, 1] == 1) { :
  the condition has length > 1 and only the first element will be used</p>

<p>Any help debugging the script would be appreciated! </p>