title: Using apply functions instead of for loops in R
body: <p>I have been trying to replace a for loop in my code with an apply function, and i attempted to do it in all the possible ways, using sapply and lapply and apply and mapply, always seems to not work out, the original function looks like this</p>
  
  <pre class="lang-r prettyprint-override"><code>ds1 &lt;- data.frame(col1 = c(NA, 2), col2 = c("A", "B"))
  ds2 &lt;- data.frame(colA = c("A", "B"), colB = c(90, 110))
  
  for(i in 1:nrow(ds1)){
    if(is.na(ds1$col1[i])){
      ds1$col1[i] &lt;- ds2[ds2[,"colA"] == ds1$col2[i], "colB"]
    }
  }
  </code></pre>
  
  <p>My latest attempt with the apply family looks like this</p>
  
  <pre class="lang-r prettyprint-override"><code>ds1 &lt;- data.frame(col1 = c(NA, 2), col2 = c("A", "B"))
  ds2 &lt;- data.frame(colA = c("A", "B"), colB = c(90, 110))
  
  sFunc &lt;- function(x, y, z){
    if(is.na(x)){
      return(z[z[,"colA"] == y, "colB"])
    } else {
      return(x)
    }
  }
  
  ds1$col1 &lt;- sapply(ds1$col1, sFunc, ds1$col2, ds2)
  </code></pre>
  
  <p>Which returns <code>ds2$colB</code> for each row, can someone explain to me what I got wrong about this?</p>