title: Change class of multiple columns in data frame without for loop
body: <p>I want to change the class of multiple columns in an R data frame without either doing it one by one, or using a <code>for</code> loop (and noting <a href="https://stackoverflow.com/questions/3796266/change-the-class-of-many-columns-in-a-data-frame">this</a> answer). I <em>can</em> do it with either of these methods, but they feel clumsy. Note that I don't necessarily want to change every column.</p>
  
  <p>E.g. I have data frame <code>mydf</code>:</p>
  
  <pre><code>mydf &lt;- data.frame("col1" = c(1, 2, 3),
                 "col2" = c("a", "b", "c"),
                 "col3" = c("a", "a", "b"), stringsAsFactors = FALSE)
  </code></pre>
  
  <p>I want to change columns two and three to class factor. (In reality I want to deal with many more than two columns...)</p>
  
  <p>I can either do it column by column in my favourite way, e.g.:</p>
  
  <pre><code>mydf$col2     &lt;- as.factor(mydf$col2)
  mydf[, 3]     &lt;- as.factor(mydf[,3])
  </code></pre>
  
  <p>Or I could use a for loop:</p>
  
  <pre><code> for (i in 2:3{
     mydf[,i] &lt;- as.factor(mydf[,i])
   }
  </code></pre>
  
  <p>These <em>work</em>, but feel clunky and suboptimal.</p>
  
  <p>Better ideas?</p>