prefered way to convert list or data.frame into a vector by column

What's the prefered way to convert a data.frame into a vector?
Following code shows that the results are equal.

x <- data.frame(matrix(rnorm(30), nrow = 10))
r1 <- c(x, recursive = TRUE, use.names = FALSE)
r2 <- as.vector(as.matrix(x))
all.equal(r1, r2)
identical(r1, r2)

I'd guess c() is the way to go since it's primitive see Chapter 2 or by calling c.

microbenchmark::microbenchmark(
r1 = c(x, recursive = TRUE, use.names = FALSE),
r2 = as.vector(as.matrix(x)),
times = 1000L)
Unit: nanoseconds
 expr   min    lq    mean median    uq    max neval
   r1   600   700  1053.7   1000  1200   9600  1000
   r2 35900 37000 41604.6  37800 42100 132900  1000

c is 40x faster on my machine, if speed is of the essence.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.