Misha
Misha

Reputation: 3126

double nesting with tidyverse and purrr

I´d like to create a double nested data structure, where c is nested in a which is further nested within 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)

So the first nest is OK. But I´d like to further nest within m2$one.

any idea how I can do this?

I can go:

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

but this gives another column within m3, not within m2$one.

Upvotes: 6

Views: 565

Answers (1)

aosmith
aosmith

Reputation: 36076

You can replace the single-nested column one with the new double-nested column in mutate by assigning the same name (one) to the result rather than making a new column as you did.

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

Upvotes: 5

Related Questions