Comparison of two great answers
There are two great one liner suggestions in this thread:
(1) cbind(df[1], t(data.frame(df$b)))
This is from @Onyambu
using base
R. To get to this answer one needs to know that a dataframe
is a list and needs a bit of creativity.
(2) df %>% unnest_wider(b)
This is from @iago
using tidyverse
. You need extra packages and to know all the nest
verbs, but one can think that it is more readable.
Now let's compare performance
library(dplyr)
library(tidyr)
library(purrr)
library(microbenchmark)
N <- 100
df <- tibble(a = 1:N, b = map2(1:N, 1:N, c))
tidy_foo <- function() suppressMessages(df %>% unnest_wider(b))
base_foo <- function() cbind(df[1],t(data.frame(df$b))) %>% as_tibble # To be fair
microbenchmark(tidy_foo(), base_foo())
Unit: milliseconds
expr min lq mean median uq max neval
tidy_foo() 102.4388 108.27655 111.99571 109.39410 113.1377 194.2122 100
base_foo() 4.5048 4.71365 5.41841 4.92275 5.2519 13.1042 100
Aouch!
base
R solution is 20 times faster.