title: For loop vs if/else in R
body: <p>I am struggling to understand why these two bits of code are producing drastically different results: </p>
  
  <p>First some functions: </p>
  
  <pre><code>n &lt;- 5000
  alpha1 &lt;- rep(NA, n)
  Y &lt;- c(replicate(n, sample(c(-1, 1), 1, prob=c(1/2, 1/2))))
  
  conditional_sampler &lt;- function(x){      
      sample(c(-1, 1), 1, prob = c(x, 1-x))
    }
  
   t &lt;- .4
  
    lower &lt;- function(t){
      runif(1,(.4-t),.4)
    }
  
    upper &lt;- function(t){
      runif(1,.6,(.6+t))
    }
  </code></pre>
  
  <p>Now the code: </p>
  
  <pre><code>alpha1 &lt;- ifelse(Y==1, conditional_sampler(lower(t)), conditional_sampler(upper(t)))
  </code></pre>
  
  <p>vs. </p>
  
  <pre><code> for (i in 1:n){
      if (Y[i]==1) {
        alpha1[i] &lt;- conditional_sampler(lower(t))}
      else {
        alpha1[i] &lt;- conditional_sampler(upper(t))}}
  </code></pre>
  
  <p>Any help would be much appreciated.</p>