Unnest a list of vectors in a data frame in R

Viewed 320

I have the following data frame:

library(dplyr)

tibble(
  x = 1:5000,
  y = rnorm(5000),
  z = list(seq(1, 100, 10))
)
#> # A tibble: 5,000 x 3
#>        x       y z         
#>    <int>   <dbl> <list>    
#>  1     1 -0.0973 <dbl [10]>
#>  2     2 -1.65   <dbl [10]>
#>  3     3 -0.636  <dbl [10]>
#>  4     4 -1.33   <dbl [10]>
#>  5     5 -0.177  <dbl [10]>
#>  6     6 -0.271  <dbl [10]>
#>  7     7  0.506  <dbl [10]>
#>  8     8 -1.07   <dbl [10]>
#>  9     9 -1.28   <dbl [10]>
#> 10    10 -1.31   <dbl [10]>
#> # … with 4,990 more rows

The column z is a vector, for example:

seq(1, 100, 10)
#>  [1]  1 11 21 31 41 51 61 71 81 91

And each one of these vector elements should be a column. Therefore, this is my expected output (note that I don't care about the name of columns):

#> # A tibble: 5,000 x 12
#>        x      y  ...1  ...2  ...3  ...4  ...5  ...6  ...7  ...8  ...9 ...10
#>    <int>  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#>  1     1  1.62      1    11    21    31    41    51    61    71    81    91
#>  2     2  1.45      1    11    21    31    41    51    61    71    81    91
#>  3     3 -1.61      1    11    21    31    41    51    61    71    81    91
#>  4     4  1.09      1    11    21    31    41    51    61    71    81    91
#>  5     5  3.16      1    11    21    31    41    51    61    71    81    91
#>  6     6  0.313     1    11    21    31    41    51    61    71    81    91
#>  7     7 -1.11      1    11    21    31    41    51    61    71    81    91
#>  8     8  1.50      1    11    21    31    41    51    61    71    81    91
#>  9     9 -1.01      1    11    21    31    41    51    61    71    81    91
#> 10    10  0.149     1    11    21    31    41    51    61    71    81    91
#> # … with 4,990 more rows

I can achieve the above using tidyr::unnest_wider():

library(dplyr)
library(tidyr)

tibble(
  x = 1:5000,
  y = rnorm(5000),
  z = list(seq(1, 100, 10))
) %>% 
  unnest_wider(col = z)

But the issue is that this is rather slow for big data frames. I was wondering if there is another way to achieve the same goal using a faster function?

1 Answers

So, this I believe is much faster than unnest_wider, there can be other options as well.

library(tidyverse)
d <- data %>% 
     cbind(., do.call('rbind', .$z)) %>% 
     select(-z)
Related