与 tidyverse 和 purrr 的双重嵌套

double nesting with tidyverse and purrr

我想创建一个双层嵌套数据结构,其中 c 嵌套在 a 中,a 进一步嵌套在 id 中。

library(tidyverse)
m<-data_frame(id=c(100,101,100,101,100,101,100,101),
            a=c("A","A","B","B","A","A","D","D"),
            c=c(1:8))
m2 <- m %>%
group_by(id) %>%
nest(.key = one)

所以第一个巢就OK了。但我想进一步嵌套在 m2$one 中。

知道我该怎么做吗?

我可以去:

        m3 <- m2 %>%
              mutate(
                     two=map(m2$one,~(.x %>% 
                                      group_by(a) %>%
                                      nest(.key=two)))
              )

但这给出了 m3 中的另一列,而不是 m2$one 中的另一列。

您可以将 single-nested 列 one 替换为 mutate 中的新 double-nested 列,方法是为结果指定相同的名称 (one)而不是像您那样创建一个新专栏。

m2 %>%
    mutate(one = map(one, ~.x %>% 
                        group_by(a) %>%
                        nest(.key = two)))