title: Using vapply instead of sapply
body: <p>I am reading Advanced R by Hadley available at <a href="http://adv-r.had.co.nz/Functionals.html" rel="nofollow noreferrer">http://adv-r.had.co.nz/Functionals.html</a>. He talks about the difference between <code>sapply</code> and <code>vapply</code>. My question is relating to using <code>vapply</code> instead of <code>sapply</code>, which he doesn't discuss further in his example.</p>
  
  <p>Here's his code:</p>
  
  <pre><code>df2 &lt;- data.frame(x = 1:10, y = Sys.time() + 1:10)
  sapply(df2, class)
  </code></pre>
  
  <p>This returns </p>
  
  <pre><code>$x
  [1] "integer"
  
  $y
  [1] "POSIXct" "POSIXt"
  </code></pre>
  
  <p>However, when I run <code>vapply</code>, I get an error. </p>
  
  <pre><code>vapply(df2, class, character(1))
  </code></pre>
  
  <p>Error:</p>
  
  <pre><code>Error in vapply(df2, class, character(1)) : values must be length 1,
   but FUN(X[[2]]) result is length 2
  </code></pre>
  
  <p>I have two questions:</p>
  
  <p><strong>Question:1)</strong> When I replace character(1) with character(2), it gives me the following error message: </p>
  
  <pre><code>vapply(df2, class, character(2))
  Error in vapply(df2, class, character(2)) : values must be length 2,
   but FUN(X[[1]]) result is length 1
  </code></pre>
  
  <p>Why does this happen?</p>
  
  <p><strong>Question:2)</strong> How do I use <code>vapply</code> instead of <code>sapply</code>?</p>
  
  <p>I am learning R so your answers will help me understand R at a deeper level. I'd appreciate your thoughts.</p>