如何无需unnest实现嵌套数据框的类反向hoist式分组还原?
实现嵌套数据框的反向分组(无需
unnest()) 你可以通过分组后合并列表列并嵌入原分组列的方式实现需求,全程不需要展开嵌套数据框(unnest()),核心思路是直接操作嵌套的子数据框,将需要撤销的分组列并入子框后再合并。
步骤示例
首先创建初始数据和嵌套数据框:
library(dplyr) library(tidyr) library(purrr) # 需要用到pmap/map2 set.seed(22) flavor <- data.frame( temperature = sample(x = c('hot', 'cold'), size = 1500, replace = TRUE), color = sample(c('red', 'blue', 'green'), 1500, TRUE), texture = sample(c('crumbly', 'crispy', 'wet', 'soft'), 1500, TRUE), flavor = sample.int(n = 100, size = 1500, replace = TRUE) / 100 ) # 初始的双分组嵌套结果 nested_df <- flavor %>% group_by(color, temperature) %>% nest()
核心转换代码
# 将temperature分组列并入子数据框,合并为按color分组的嵌套结构 result <- nested_df %>% group_by(color) %>% summarize( data = list( bind_rows( pmap(list(data, temperature), ~ mutate(.x, temperature = .y)) ) ), .groups = "drop_last" ) # 查看结果 result # A tibble: 3 × 2 # Groups: color [3] color data <chr> <list> 1 blue <tibble [507 × 3]> 2 green <tibble [494 × 3]> 3 red <tibble [499 × 3]>
代码解释
group_by(color):切换到目标分组维度pmap(list(data, temperature), ~ mutate(.x, temperature = .y)):把每个子数据框和对应的temperature值绑定,给子数据框添加temperature列bind_rows():将同一color下的所有子数据框合并为单个大子框list():将合并后的子框重新包裹为列表列,保持嵌套结构
更简洁的替代方案(dplyr 1.1.0+)
如果使用较新版本的dplyr,可以用reframe()简化语法:
result_reframe <- nested_df %>% group_by(color) %>% reframe( data = list( bind_rows( map2(data, temperature, ~ mutate(.x, temperature = .y)) ) ) )
这种方式避免了unnest()再重新嵌套的性能损耗,尤其适合处理大型数据集时直接操作嵌套结构完成转换。
内容的提问来源于stack exchange,提问作者Brandon
相关产品推荐
相关产品推荐

