A nested data frame is a data frame where one (or more) columns is a list of data frames. You can create simple nested data frames by hand:
(It is possible to create list-columns in regular data frames, not just in tibbles, but it’s considerably more work because the default behaviour of
data.frame() is to treat lists as lists of columns.)
But more commonly you’ll create them with
I think nesting is easiest to understand in connection to grouped data: each row in the output corresponds to one group in the input. We’ll see shortly this is particularly convenient when you have other per-group objects.
The opposite of
unnest(). You give it the name of a list-column containing data frames, and it row-binds the data frames together, repeating the outer columns the right number of times to line up.
df1 %>% unnest(data) #> # A tibble: 4 x 3 #> g x y #> <dbl> <dbl> <dbl> #> 1 1 1 2 #> 2 2 4 6 #> 3 2 5 7 #> 4 3 10 NA
Nested data is a great fit for problems where you have one of something for each group. A common place this arises is when you’re fitting multiple models.
Once you have a list of data frames, it’s very natural to produce a list of models:
And then you could even produce a list of predictions:
This workflow works particularly well in conjunction with broom, which makes it easy to turn models into tidy data frames which can then be
unnest()ed to get back to flat data frames. You can see a bigger example in the broom and dplyr vignette.