首页 > 解决方案 > 如何在 group_nest 之后取消嵌套 tibble?

问题描述

这是通过一些分组列收集一些数据的代码:

df <- tibble(data.frame(x=c(1,2,3), y=c(4,5,6)))
vars <- c('x', 'y')
df2 <- df %>%
    group_nest(grouping_=across(all_of(vars))) %>%
    mutate(result=1, data=NULL) %>%
    unnest(cols=result)

现在 df2 有一个 grouping_ 数据框列,其中包含两个元素(x 和 y):

> str(df2)
tibble [3 × 2] (S3: tbl_df/tbl/data.frame)
 $ grouping_: tibble [3 × 2] (S3: tbl_df/tbl/data.frame)
  ..$ x: num [1:3] 1 2 3
  ..$ y: num [1:3] 4 5 6
 $ result   : num [1:3] 1 1 1

如何展平 df2 以获得具有三列(x、y、结果)的数据框?

我无法工作:

> unnest(df2, cols=grouping_)
Error: Assigned data `map(data[[col]], as_df, col = col)` must be compatible with existing data.
x Existing data has 3 rows.
x Assigned data has 2 rows.
ℹ Only vectors of size 1 are recycled.

我正在使用 tidyverse 1.3.0,因此使用 dplyr 1.0.0。

编辑:这是一个hacky方式:

cbind(df2$grouping_,
      df2 %>% mutate(grouping_=NULL))

也许这是最好的方式。

标签: rdplyr

解决方案


尝试使用summarize()而不是unnest().

df2 <- df %>%
  group_nest(grouping_=across(all_of(vars))) %>%
  mutate(result=1, data=NULL) %>% 
  summarize(grouping_, result)

df2 
# A tibble: 3 x 3
      x     y result
  <dbl> <dbl>  <dbl>
1     1     4      1
2     2     5      1
3     3     6      1

str(df2)
tibble [3 x 3] (S3: tbl_df/tbl/data.frame)
 $ x     : num [1:3] 1 2 3
 $ y     : num [1:3] 4 5 6
 $ result: num [1:3] 1 1 1

推荐阅读