24.6 Avoiding Input Coercion
as.data.frame()
is quite slow because it coerces each element into a data frame and thenrbind()
s them together- instead, if you have a named list with vectors of equal length, you can directly transform it into a data frame
quickdf <- function(l) {
class(l) <- "data.frame"
attr(l, "row.names") <- .set_row_names(length(l[[1]]))
l
}
l <- lapply(1:26, function(i) runif(1e3))
names(l) <- letters
bench::mark(
as.data.frame = as.data.frame(l),
quick_df = quickdf(l)
)[c("expression", "min", "median", "itr/sec", "n_gc")]
#> # A tibble: 2 × 4
#> expression min median `itr/sec`
#> <bch:expr> <bch:tm> <bch:tm> <dbl>
#> 1 as.data.frame 959.5µs 1.01ms 973.
#> 2 quick_df 6.3µs 7.08µs 132966.
Caveat! This method is fast because it’s dangerous!