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.
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.
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.
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() .
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.
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With