Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

double nesting with tidyverse and purrr

Tags:

r

purrr

tidyverse

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.

like image 899
Misha Avatar asked Feb 11 '17 18:02

Misha


People also ask

What does Nest () do in R?

Nesting creates a list-column of data frames; unnesting flattens it back out into regular columns. Nesting is implicitly a summarising operation: you get one row for each group defined by the non-nested columns. This is useful in conjunction with other summaries that work with whole datasets, most notably models.

How do you Unnest in R?

The tidyr package in R is used to “tidy” up the data. The unnest() method in the package can be used to convert the data frame into an unnested object by specifying the input data and its corresponding columns to use in unnesting. The output is produced in the form of a tibble in R.

How do you make a nested Dataframe in R?

Or more commonly, we can create nested data frames using tidyr::nest() . df %>% nest(x, y) specifies the columns to be nested; i.e. the columns that will appear in the inner data frame. Alternatively, you can nest() a grouped data frame created by dplyr::group_by() .

What are Tibbles in R?

Tibble is a package in the R programming language that is used to manipulate and print data frames. It is the latest method for reimagining a data frame. It keeps all the crucial features regarding the data frame.


1 Answers

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)))
like image 71
aosmith Avatar answered Oct 06 '22 03:10

aosmith