I have the following tibble, which has two nested columns:
library(tidyverse)
df <- structure(list(a = list(c("a", "b"), "c"), b = list(c("1", "2",
"3"), "3"), c = c(11, 22)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -2L))
Which produces:
# A tibble: 2 x 3
a b c
<list> <list> <dbl>
1 <chr [2]> <chr [3]> 11
2 <chr [1]> <chr [1]> 22
How can I unnest them at once producing one single tibble?
I tried this but fail:
> df %>% unnest(a, b)
Error: All nested columns must have the same number of elements.
There's probably a cleaner way to do it, but if you want the cartesian product for the columns you can unnest them in sequence, if nothing else:
> df %>%
unnest(a, .drop = FALSE) %>%
unnest(b, .drop = FALSE)
# # A tibble: 7 x 3
# c a b
# <dbl> <chr> <chr>
# 1 11 a 1
# 2 11 a 2
# 3 11 a 3
# 4 11 b 1
# 5 11 b 2
# 6 11 b 3
# 7 22 c 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With