我有以下小标题,其中有两个嵌套的列:
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))
哪个会产生:
# A tibble: 2 x 3
a b c
<list> <list> <dbl>
1 <chr [2]> <chr [3]> 11
2 <chr [1]> <chr [1]> 22
我如何一次将它们嵌套在一起呢?
我尝试了这个但失败了:
> df %>% unnest(a, b)
Error: All nested columns must have the same number of elements.
答案 0 :(得分:2)
可能有一种更清洁的方法,但是,如果您想要列的笛卡尔乘积,则可以按顺序取消嵌套它们,如果没有其他情况:
> 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