title: R sapply vs apply vs lapply + as.data.frame
body: <p>I'm working with some <code>Date</code> columns and trying to cleanse for obviously incorrect dates.  I've written a function using the <code>safe.ifelse</code> function mentioned <a href="https://stackoverflow.com/questions/6668963/how-to-prevent-ifelse-from-turning-date-objects-into-numeric-objects">here</a>.</p>
  
  <p>Here's my toy data set:</p>
  
  <pre><code>df1 &lt;- data.frame(id = 1:25
      , month1 = seq(as.Date('2012-01-01'), as.Date('2014-01-01'), by = 'month'  )
      , month2 = seq(as.Date('2012-01-01'), as.Date('2014-01-01'), by = 'month'  )
      , month3 = seq(as.Date('2012-01-01'), as.Date('2014-01-01'), by = 'month'  )
      , letter1 = letters[1:25]
      )
  </code></pre>
  
  <p>This works fine for a single column:</p>
  
  <pre><code>df1$month1 &lt;- safe.ifelse(df1$month1 &gt; as.Date('2013-10-01'), as.Date('2013-10-01'), df1$month1)
  </code></pre>
  
  <p>As I have multiple columns I'd like to use a function and apply to take care of all <code>Date</code> columns at once:</p>
  
  <pre><code>capDate &lt;- function(x){
  today1 &lt;- Sys.Date()
      safe.ifelse &lt;- function(cond, yes, no){ class.y &lt;- class(yes)
                                    X &lt;- ifelse(cond,yes,no)
                                    class(X) &lt;-class.y; return(X)}
  
      x &lt;- safe.ifelse(as.Date(x) &gt; as.Date(today1), as.Date(today1), as.Date(x))
   }
  </code></pre>
  
  <p>However when I try to use <code>sapply()</code></p>
  
  <pre><code>df1[,dateCols1] &lt;- sapply(df1[,dateCols1], capDate)
  </code></pre>
  
  <p>or <code>apply()</code></p>
  
  <pre><code>df1[,dateCols1] &lt;- apply(df1[,dateCols1],2, capDate))
  </code></pre>
  
  <p>the <code>Date</code> columns lose their <code>Date</code> formatting.  The only way I've found to get around this is by using <code>lapply()</code> and then converting back to a <code>data.frame()</code>.  Can anyone explain this?</p>
  
  <pre><code>df1[,dateCols1] &lt;- as.data.frame(lapply(df1[,dateCols1], capDate))
  </code></pre>