data |>
pivot_wider(
names_from = ______,
values_from = ______)Pivoting Wider
Now we’ll use pivot_wider to take a long format dataset and reshape it into wide format. You probably won’t do this quite as often as pivoting longer, but it is still occasionally useful, especially for changing data to be in an easy-to-read format.
The basic syntax for this function is to get the name of the column you want to expand into more columns and the name for the column containing the values you want to populate the data. The most basic version of the code will look like this:
First let’s just turn our long version of the billboard data back into wide format. As a reminder here’s what the long data looks like:
To change it back we’ll take the names from the week column and the values from the rank column:
Note that you don’t use quotes around the column names because they already exist, we aren’t creating them. Now you should see the same dataset that we started with. Run this to verify:
We’ll use another built-in dataset called ChickWeight to demonstrate. This dataset measures the weight of baby chicks over time to see if there is a difference between four diets. Here’s the data in its current long format. (It’s quite long.)
We want to rearrange the table so that there are different columns for every time point and the weights are listed under those columns. See if you can add to this code:
You should see the first ten rows of the rearranged dataset where the columns are now Chick, Diet, and even numbers 0-20.
That’s the gist of pivot_wider().