首页 > 解决方案 > 在 tidyr 版本 1.0.0 中,如何将嵌套列简化为列表?

问题描述

我刚刚注意到nest()更新的 tidyr 的行为发生了变化。以前,如果您嵌套单个列,它将返回一个列表列,这使得在所述列表中搜索变得容易,例如,获取“最高”分类。例如:

tribble(
  ~a,   ~b,   ~c,   ~class,   ~lots_of_other_vars,
  1,    100,  150,  "lowest",  "blah",
  1,    100,  150,  "medium",  "blah",
  1,    100,  150,  "highest", "blah",
  2,    5000, 5500, "lowest",  "blah",
  2,    5000, 5500, "medium",  "blah",
  3,    342,  350,  "lowest",  "blah"
) %>% 
  nest(class) %>%
  mutate(class = case_when(
    "highest" %in% data ~ "highest",
    "medium" %in% data ~ "medium",
    TRUE ~ "lowest"
  ))

不幸的是,最新版本的嵌套函数不是返回一个简单的列表,而是返回一个列表 ( list(df[,1])) 内的数据框,从而破坏了我的代码。

当然,我可以用group_by其他方法得到类似的结果:

tribble(
  ~a,   ~b,   ~c,   ~class,   ~lots_of_other_vars,
  1,    100,  150,  "lowest",  "blah",
  1,    100,  150,  "medium",  "blah",
  1,    100,  150,  "highest", "blah",
  2,    5000, 5500, "lowest",  "blah",
  2,    5000, 5500, "medium",  "blah",
  3,    342,  350,  "lowest",  "blah"
) %>% 
  group_by_at(vars(-class)) %>% 
  mutate(overall_class = case_when(
    "highest" %in% class ~ "highest",
    "medium" %in% class ~ "medium",
    TRUE ~ "lowest"
  )) %>% 
  select(-class) %>% 
  distinct()

但是,这是一个简化的场景,我更愿意保留类列表以便稍后查看。鉴于对 的更改nest,在对其他变量调用 distinct 时获取 class 值列表的最简单方法是什么(即,嵌套曾经做什么)?

编辑

这就是我想要的加上一列,其中列出了为该站点观察到的所有类的列表:

     a     b     c lots_of_other_vars highest_support
  <dbl> <dbl> <dbl> <chr>              <chr>          
1     1   100   150 blah               highest        
2     2  5000  5500 blah               medium         
3     3   342   350 blah               lowest

标签: rdplyrtidyversetidyr

解决方案


推荐阅读