1. Nesting for multiple models
In these next two sections, we're going to discuss fitting many models: in particular,
2. One model for each country
fitting one model for each country. This will allow us to find the countries whose level of agreement with the rest of the United Nations is increasing or decreasing most dramatically.
Fitting multiple models requires several steps.
3. Start with one row per country
First, we start with the by_year_country dataset, containing one row for each combination of year and country. We need to separate this data out by country so we can model them individually. But instead of just pulling out one, as we've done before, we're going to split it into many small datasets, one for each country.
4. nest() turns it into one row per country
To do this, we use nest from the tidyr package. Using nest-negative country means to nest all the columns besides country. which means we end up with a data frame with one row for each country. All the other columns- year, total, and percent_yes- have been nested into a column called data. This is a list column, which we haven't seen before. It allows each item in the column to itself be a data frame (specifically a tibble, dplyr's version of a data frame)- containing the other columns. This means we now have a filtered version for Afghanistan, a filtered version for Argentina, and so on. In the next lesson this will allow us to fit a model to each.
5. unnest() does the opposite
Later we'll want to take a nested list column and bring the rows from each individual back into the "top level" of the data frame. This is done with the function unnest. Pipe the table in, saying you want to unnest the data column, and it takes each of those sub-tables and puts their rows back into the main table, where we get to the data we started from.
You might be wondering why we nested the data frame only to reverse it right after. In the next lesson we'll add a step between the nesting and unnesting, where we fit a model to each sub-table and tidy it, that will make this process useful
6. Let's practice!