sapply()
is dangerous for programmatic usage because it is type-unstable:
you can't predict in advance what it's going to return just be reading the
code. Instead use vapply()
, which has an additional argument FUN.VALUE
,
that
Examples
df <- data.frame(
a = 1,
b = "a",
c = Sys.time(),
d = ordered("a"),
stringsAsFactors = FALSE
)
# A list
base::sapply(df, class)
#> $a
#> [1] "numeric"
#>
#> $b
#> [1] "character"
#>
#> $c
#> [1] "POSIXct" "POSIXt"
#>
#> $d
#> [1] "ordered" "factor"
#>
# A matrix
base::sapply(df[3:4], class)
#> c d
#> [1,] "POSIXct" "ordered"
#> [2,] "POSIXt" "factor"
# A vector
base::sapply(df[1:2], class)
#> a b
#> "numeric" "character"