【问题标题】:Include the grouping column in nested data在嵌套数据中包含分组列
【发布时间】:2021-06-04 11:22:45
【问题描述】:

我想对每组变量 ab 运行一些建模。问题是nest() 不包含模型所需的分组变量。

expand.grid(a = LETTERS[1:3], b = LETTERS[1:2], c=1:3, d=1:3) %>% 
   group_by(a, b) %>% 
   nest()

结果表在“外部”包括ab,在嵌套的小标题中包括cd。如何将ab 添加到嵌套的小标题中?

【问题讨论】:

    标签: r purrr


    【解决方案1】:

    使用 cur_data_all() 创建一个 3 列数据框,其中最后一列嵌套是一个列表,每个列表的组成部分是一个 a、b 组中的 4 列数据框。

    ans <- expand.grid(a = LETTERS[1:3], b = LETTERS[1:2], c=1:3, d=1:3) %>% 
       group_by(a, b) %>% 
       summarize(nest = list(cur_data_all()), .groups = "drop")
    

    给予:

    > ans
    # A tibble: 6 x 3
      a     b     nest            
      <fct> <fct> <list>          
    1 A     A     <tibble [9 x 4]>
    2 A     B     <tibble [9 x 4]>
    3 B     A     <tibble [9 x 4]>
    4 B     B     <tibble [9 x 4]>
    5 C     A     <tibble [9 x 4]>
    6 C     B     <tibble [9 x 4]>
    
    > names(ans$nest[[1]])
    [1] "a" "b" "c" "d"
    

    如果一个只有一个 ccolumn 的数据框,nest,需要等于上面的嵌套列(属性除外),那么这个代码就可以工作。

    expand.grid(a = LETTERS[1:3], b = LETTERS[1:2], c=1:3, d=1:3) %>% 
      group_modify(~ tibble(nest = group_split(., a, b)))
    

    【讨论】:

      猜你喜欢
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-13
      • 2019-11-10
      • 1970-01-01
      • 2021-11-06
      • 2021-11-17
      相关资源
      最近更新 更多