How to manipulate multilevel nested data frames in R?

Viewed 40

Imagine that there is a data frame df, which contains a nested data frame column sub_df. Each sub_df contains a nested data frame column called sub_sub_df. Each one of these also contain a nested data frame. etc. So we have a multilevel nested data frame, with an arbitrary number of levels.

If I want to calculate (mutate) something on the 3rd level e.g. sub_sub_df, what would be the best way to do this? I assume there is a function or notation, where I could manipulate giving the "address" of the level, which I would change.

I could use multiple levels of mutate inside purrr::map inside mutate. But the code will not be readable at all.

I wonder, if there is an easier and a cleaner way for such operations?

Here is an example data frame:

library(tidyr)

df = data.frame(
    id = 1:8,
    sub_id = rep(1:2, each = 4),
    sub_sub_id = rep(1:2, each = 2, 2),
    sub_sub_sub_id = rep(1:8)
)

df = df %>% nest(sub_sub_sub_df = sub_sub_sub_id) %>%
    nest(sub_sub_df = c(sub_sub_id, sub_sub_sub_df)) %>%
    nest(sub_df = c(sub_id, sub_sub_df))
0 Answers
Related