title: Function to replace outliers with NA using R
body: <p>Let's say I have the following sample data set:</p>
  
  <pre><code>set.seed(20130828)
      data &lt;- data.frame(X = c(NA, rnorm(1000), runif(20, -20, 20)), 
      Y = c(runif(1000), 
      rnorm(20, 2), NA), Z = c(rnorm(1000, 1), NA, runif(20)))
  </code></pre>
  
  <p>Using the next function, I have identified outliers, which are observations outside 3 sd:</p>
  
  <pre><code>findOutlier &lt;- function(data, cutoff = 3) {
      sds &lt;- apply(data, 2, sd, na.rm = TRUE)
      result &lt;- mapply(function(d, s) {
          which(d &gt; cutoff * s)
      }, data, sds)
      result
  }
  
  outliers &lt;- findOutlier(data)
  </code></pre>
  
  <p>Now I need to replace all outliers with NA. I used the following function:</p>
  
  <pre><code>OutliersToNA &lt;- function(data, outliers) {
  result &lt;- mapply(function(d, o) {
      res &lt;- d
      res[o] &lt;- NA
      return(res)
  }, data, outliers)
  return(as.data.frame(result))
  </code></pre>
  
  <p>}</p>
  
  <p>It returns the following error: </p>
  
  <pre><code> Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  : 
    arguments imply differing number of rows: 4, 0, 1, 2, 3 
  </code></pre>
  
  <p>Can you please suggest any improvements to the function to replace outliers with NA?</p>