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