data |>
pivot_longer(
cols = _____,
names_to = _____,
values_to = _____)Pivoting Longer
To take wide format data and make it longer we use the pivot_longer() function from the {tidyr} package (which is loaded when you load {tidyverse}).
The general format of this function is to name the columns around which you want to pivot, set the name of the new column for these will go to, and give a name to the new column where the values to go. The code structure looks like this:
In the simple example, we want to turn day1, day2, day3 into a single column called day. Then we’ll created a new column called measurement for the cell values to be reshuffled into. So our code would be
data |>
pivot_longer(
cols = c(day1, day2, day3),
names_to = "day",
values_to = "measurement")Note that the current column names don’t have quotes around them, but the new ones that we are creating do.
Here’s a truncated version of one of R’s built-in datasets called billboard. It lists artist, song, and rank on the billboard chart by week. (The top 100 billboard songs were a thing that used to happen when people primarily listened to music on the radio.) Run the code to view the data.
Now try to pivot this table so that there is a single column for week and a new column for rank.
That’s all there is to the basics of pivoting. We’ll learn some add-ons in a moment, but first we’ll pivot wider.