How to unnest tibbles within a tibble?

Viewed 276

I have a tibble with some variables being other tibbles made of doubles. All the tibbles nested within the main tibble have the same number of rows of the main tibble.

I want to unnest all the nested tibbles to get one tibble with each variable being a vector.

%>% unnest() does not work.

Try to unnest this data

data <- tibble(col1 = 1:5, col2 = data.frame(col3 = 1:5, col4 = 5:9))

Notice that I have to unnest all the variables of data.

2 Answers

If we need to have regular columns, try with do.call and data.frame

out <-  do.call(data.frame, data)
names(out)[-1] <- names(data$col2)

-output

> out
  col1 col3 col4
1    1    1    5
2    2    2    6
3    3    3    7
4    4    4    8
5    5    5    9

Here's a neat solution in dplyr

data %>% bind_cols(.$col2) %>% select(-col2)

# A tibble: 5 × 3
   col1  col3  col4
  <int> <int> <int>
1     1     1     5
2     2     2     6
3     3     3     7
4     4     4     8
5     5     5     9
Related