Function to remove Outliers from a DataFrame
<p>I want to write a function that will take a <code>data.frame</code> as input and return a new <code>data.frame</code> that has replaced outliers using the <code>tsclean()</code> function from the forecast package.</p>

<p>For the example input <code>df</code> (containing obvious outliers):</p>

<pre><code>df &lt;- data.frame(col1 = runif(24, 400, 700),
                 col2 = runif(24, 350, 600),
                 col3 = runif(24, 600, 940),
                 col4 = runif(24, 2000, 2600),
                 col5 = runif(24, 950, 1200))

colnames(df) &lt;- c("2to2", "2to6", "17to9", "20to31", "90to90")
df$`2to2`[[12]]=10000
df$`17to9`[[20]]=6000
df$`20to31`[[8]]=12000
</code></pre>

<p>I've been trying to solve this as follows</p>

<pre><code>clean_ts &lt;- function(df, frequency = 12, start = c(2014, 1), end = c(2015, 12)) {

  ts &lt;- ts(df, frequency = frequency, start = start, end = end)
  results &lt;- list()

  for (i in 1:ncol(ts)) {
    clean &lt;- as.data.frame(tsclean(ts[,i]))
    results[[i]] &lt;- as.data.frame(cbind(clean))
  }
  return(results)
}
</code></pre>

<p>I know this is wrong. Instead of returning a list I want my function to return a <code>data.frame</code> with the same dimensions and column names as my input <code>data.frame</code>. I just want the columns of the <code>data.frame()</code> replaced according to the <code>tsclean()</code> function. So from the example my output would have the following form:</p>

<pre><code>2to2  2to6  17to9  20to31  90to90
 .     .     .       .       .
 .     .     .       .       .
</code></pre>