我希望对每组变量 a
和 b
进行建模。问题在于,nest()
不包括模型所需的分组变量。
expand.grid(a = LETTERS[1:3], b = LETTERS[1:2], c=1:3, d=1:3) %>%
group_by(a, b) %>%
nest()
生成的表格在“外部”包括
a
和b
,在嵌套的tibble中包括c
和d
。我该如何将a
和b
添加到嵌套的tibble中?使用 cur_data_all() 函数创建一个三列数据框,其中最后一列 nest 是一个列表,其中每个组件都是一个具有四列数据的 a,b 组中的数据框。
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"
expand.grid(a = LETTERS[1:3], b = LETTERS[1:2], c=1:3, d=1:3) %>%
group_modify(~ tibble(nest = group_split(., a, b)))