If you find any typos, errors, or places where the text may be improved, please let us know by providing feedback either in the feedback survey (given during class) or by using GitHub.
On GitHub open an issue or submit a pull request by clicking the " Edit this page" link at the side of this page.
9 Quickly re-arranging data with pivots
Here we will continue using the Workflow block as we cover the fourth block, “Work with project data” in Figure 9.1.
9.1 Learning objectives
The overall learning outcome for this session is to:
- Describe what long and wide data are, what pivoting means in this context, and demonstrate how to switch between the two.
Specific objectives are to:
- Describe the concept of “pivoting” data to convert data in a “long” format to a “wide” format and vice versa.
- Identify situations when data in the long or wide format are more appropriate to use.
- Apply the
pivot_longer()
andpivot_wider()
functions from the tidyr package to pivot data. - Continue extending functions to make use of pivots for processing and cleaning data.
9.2 Setup for the analysis in Quarto
We now have a working dataset to start doing some simple analyses on in the Quarto document. A recommended workflow with Quarto is to often render / “knit” it and make sure your analysis is reproducible (while on your computer). We already cleaned it up from the previous session.
We will now add the load()
code right below the source()
function in the setup
code chunk:
As we write more R code and do some simple analyses of the data, we are going to be knitting fairly often (depending on how long the analysis takes of course). The main reason for this is to ensure that whatever you are writing and coding will at least be reproducible on your computer, since Quarto is designed to ensure the document is reproducible.
9.3 Re-arranging data for easier summarizing
Since we’ll be using tidyr, we will need to add it as a dependency by running this in the Console:
Let’s try this out with mmash
. In your doc/learning.qmd
file, create a new header called ## Pivot longer
and create a new code chunk below that with Ctrl-Alt-ICtrl-Alt-I or with the Palette (Ctrl-Shift-PCtrl-Shift-P, then type “new chunk”). Now we can start typing in our code:
#> Error in `pivot_longer()`:
#> ! Can't combine `user_id` <character> and `weight` <double>.
Why the error? We get an error because we are trying to mix data types. We can’t have character data and number data in the same column. Let’s pivot only numbers.
#> # A tibble: 470 × 5
#> user_id gender samples name value
#> <chr> <chr> <chr> <chr> <dbl>
#> 1 user_1 M before sleep weight 6.5 e+1
#> 2 user_1 M before sleep height 1.69e+2
#> 3 user_1 M before sleep age 2.9 e+1
#> 4 user_1 M before sleep cortisol_norm 3.41e-2
#> 5 user_1 M before sleep melatonin_norm 1.74e-8
#> 6 user_1 M before sleep day 1 e+0
#> 7 user_1 M before sleep ibi_s_mean 6.66e-1
#> 8 user_1 M before sleep ibi_s_sd 1.64e-1
#> 9 user_1 M before sleep hr_mean 9.06e+1
#> 10 user_1 M before sleep hr_sd 1.30e+1
#> # ℹ 460 more rows
Nice! But not super useful. We can exclude specific columns from pivoting with -
before the column name, for instance with user_id
and day
. Let’s drop the samples
column before pivoting since day
gives us the same information:
#> # A tibble: 423 × 5
#> user_id gender day name value
#> <chr> <chr> <dbl> <chr> <dbl>
#> 1 user_1 M 1 weight 6.5 e+1
#> 2 user_1 M 1 height 1.69e+2
#> 3 user_1 M 1 age 2.9 e+1
#> 4 user_1 M 1 cortisol_norm 3.41e-2
#> 5 user_1 M 1 melatonin_norm 1.74e-8
#> 6 user_1 M 1 ibi_s_mean 6.66e-1
#> 7 user_1 M 1 ibi_s_sd 1.64e-1
#> 8 user_1 M 1 hr_mean 9.06e+1
#> 9 user_1 M 1 hr_sd 1.30e+1
#> 10 user_1 M 2 weight 6.5 e+1
#> # ℹ 413 more rows
9.4 Exercise: Summarise your data after pivoting
Time: 15 minutes.
Using the group_by()
and summarise()
functions we learned in Section 7.6, complete these tasks starting from this code.
- Continuing the
|>
frompivot_longer()
, usegroup_by()
to group the data bygender
,day
, andname
(the long form column produced frompivot_longer()
). - After grouping with
group_by()
, usesummarise()
andacross()
on thevalue
column and find the mean and standard deviation (put them into a named list like we did previously). Don’t forget to usena.rm = TRUE
to exclude missing values. - Stop the grouping effect with
.groups = "drop"
insummarise()
. - Run styler while in the
doc/learning.qmd
file with the Palette (Ctrl-Shift-PCtrl-Shift-P, then type “style file”). - Render the Quarto file into HTML with Ctrl-Shift-KCtrl-Shift-K or with the Palette (Ctrl-Shift-PCtrl-Shift-P, then type “render”).
- Open up the Git interface and add and commit the changes to
doc/learning.qmd
with Ctrl-Alt-MCtrl-Alt-M or with the Palette (Ctrl-Shift-PCtrl-Shift-P, then type “commit”)
Click for the solution. Only click if you are struggling or are out of time.
9.5 Pivot data to wider form
In our case, we want either gender
or day
as columns with the mean and SD values. Let’s use pivot_wider()
on day
to see differences between days.
doc/learning.qmd
#> Error in `pivot_wider()`:
#> ! Can't select columns past the end.
#> ℹ Location 10 doesn't exist.
#> ℹ There are only 5 columns.
Hmm, didn’t work. Nothing has been pivoted to wider. That’s because we are missing the value_from
argument. Since we actually have the two value_mean
and value_sd
columns that have “values” in them, we need to tell pivot_wider()
to use those two columns. Since values_from
works similar to select()
, we can use starts_with()
to select the columns starting with "values"
.
doc/learning.qmd
#> # A tibble: 18 × 10
#> gender name value_mean_1 value_mean_2 value_mean_NA
#> <chr> <chr> <dbl> <dbl> <dbl>
#> 1 M age 2.60e+1 2.60e+1 28
#> 2 M cortisol_norm 2.81e-2 6.99e-2 NaN
#> 3 M height 1.80e+2 1.80e+2 175
#> 4 M hr_mean 8.10e+1 6.69e+1 NaN
#> 5 M hr_sd 1.27e+1 1.55e+1 NaN
#> 6 M ibi_s_mean 7.60e-1 9.21e-1 NaN
#> 7 M ibi_s_sd 1.77e-1 2.78e-1 NaN
#> 8 M melatonin_norm 8.33e-9 6.96e-9 NaN
#> 9 M weight 7.53e+1 7.53e+1 70
#> 10 <NA> age NaN NaN NA
#> 11 <NA> cortisol_norm NaN NaN NA
#> 12 <NA> height NaN NaN NA
#> 13 <NA> hr_mean 7.96e+1 7.04e+1 NA
#> 14 <NA> hr_sd 1.09e+1 1.78e+1 NA
#> 15 <NA> ibi_s_mean 7.58e-1 8.56e-1 NA
#> 16 <NA> ibi_s_sd 1.14e-1 1.90e-1 NA
#> 17 <NA> melatonin_norm NaN NaN NA
#> 18 <NA> weight NaN NaN NA
#> # ℹ 5 more variables: `value_mean_-29` <dbl>, value_sd_1 <dbl>,
#> # value_sd_2 <dbl>, value_sd_NA <dbl>, `value_sd_-29` <dbl>
Now we have a different problem. There are missing values in both the day
and gender
columns that, at least in this case, we don’t want pivoted. Shouldn’t they be removed when we include na.rm = TRUE
in our code? The function of na.rm = TRUE
is not to remove NA
values, but to instead tell R to not include variables in mmash
that are NA
when calculating the mean and standard deviation. In this particular case, the columns value_mean_NA
or value_mean_-29
have NA
or NaN
values because there are no other values in the data other than NA
. Since we don’t actually care about missing days (or the random -29
day), we can remove missing values with the function called drop_na()
. We also don’t care about missing gender
values, so we’ll drop them as well. Add it in the pipe right before group_by()
.
doc/learning.qmd
mmash |>
select(-samples) |>
pivot_longer(c(-user_id, -day, -gender)) |>
drop_na(day, gender) |>
group_by(gender, day, name) |>
summarise(
across(
value,
list(
mean = \(x) mean(x, na.rm = TRUE),
sd = \(x) sd(x, na.rm = TRUE)
)
),
.groups = "drop"
) |>
pivot_wider(names_from = day, values_from = starts_with("value"))
#> # A tibble: 9 × 6
#> gender name value_mean_1 value_mean_2 value_sd_1 value_sd_2
#> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 M age 2.60e+1 2.60e+1 7.28e+0 7.28e+0
#> 2 M cortisol_n… 2.81e-2 6.99e-2 3.05e-2 5.32e-2
#> 3 M height 1.80e+2 1.80e+2 8.34e+0 8.34e+0
#> 4 M hr_mean 8.10e+1 6.69e+1 7.65e+0 6.77e+0
#> 5 M hr_sd 1.27e+1 1.55e+1 4.95e+0 7.03e+0
#> 6 M ibi_s_mean 7.60e-1 9.21e-1 7.97e-2 9.11e-2
#> 7 M ibi_s_sd 1.77e-1 2.78e-1 8.60e-2 1.25e-1
#> 8 M melatonin_… 8.33e-9 6.96e-9 6.71e-9 6.39e-9
#> 9 M weight 7.53e+1 7.53e+1 1.31e+1 1.31e+1
Now that that works, let’s render the document to HTML with Ctrl-Shift-KCtrl-Shift-K or with the Palette (Ctrl-Shift-PCtrl-Shift-P, then type “render”).
9.6 Exercise: Convert this code into a function
Time: 15 minutes.
Using the same workflow we’ve been doing throughout this course, convert the code we just wrote above into a function.
- Name the function
tidy_summarise_by_day
. - Create one argument called
data
. Create a new variable inside the function calleddaily_summary
and put it inreturn()
so the function outputs it. - Test that the function works.
- Add Roxygen documentation with Ctrl-Shift-Alt-RCtrl-Shift-Alt-R or with the Palette (Ctrl-Shift-PCtrl-Shift-P, then type “roxygen comment”) and use explicit function calls with
packagename::
.- Don’t forget, you can use
?functionname
to find out which package the function comes from.
- Don’t forget, you can use
- Move (cut and paste) the newly created function over into the
R/functions.R
file. - Run styler while in the
R/functions.R
file with the Palette (Ctrl-Shift-PCtrl-Shift-P, then type “style file”). - Restart R with Ctrl-Shift-F10Ctrl-Shift-F10 or with the Palette (Ctrl-Shift-PCtrl-Shift-P, then type “restart”), go into the
doc/learning.qmd
file and run thesetup
code chunk in the Quarto document with thesource()
andload()
commands. Then test that the new function works in a code chunk at the bottom of the document. - Render the Quarto document to HTML with Ctrl-Shift-KCtrl-Shift-K or with the Palette (Ctrl-Shift-PCtrl-Shift-P, then type “render”).
- Add and commit the changes to the Git history with Ctrl-Alt-MCtrl-Alt-M or with the Palette (Ctrl-Shift-PCtrl-Shift-P, then type “commit”).
Click for the solution. Only click if you are struggling or are out of time.
#' Calculate tidy summary statistics by day.
#'
#' @param data The MMASH dataset.
#'
#' @return A data.frame/tibble.
#'
tidy_summarise_by_day <- function(data) {
daily_summary <- data |>
dplyr::select(-samples) |>
tidyr::pivot_longer(c(-user_id, -day, -gender)) |>
tidyr::drop_na(day, gender) |>
dplyr::group_by(gender, day, name) |>
dplyr::summarise(
dplyr::across(
value,
list(
mean = \(x) mean(x, na.rm = TRUE),
sd = \(x) sd(x, na.rm = TRUE)
)
),
.groups = "drop"
) |>
tidyr::pivot_wider(
names_from = day,
values_from = dplyr::starts_with("value")
)
return(daily_summary)
}
# Testing that the function works.
mmash |>
tidy_summarise_by_day()
9.7 Extending the function to use other statistics and to be tidier
Now that we’ve made the tidy summary code into a function, let’s make it more generic so we can use other summary statistics and to have the output be a bit tidier. For instance, it would be nice to be able to do something like this (we’d still have to use na.rm
though):
mmash |>
tidy_summarise_by_day(\(x) median(x, na.rm = TRUE))
mmash |>
tidy_summarise_by_day(\(x) max(x, na.rm = TRUE))
mmash |>
tidy_summarise_by_day(
list(
median = \(x) median(x, na.rm = TRUE),
max = \(x) max(x, na.rm = TRUE)
)
)
Before we get to adding this functionality, let’s first make it so the function has a tidier output. Specifically, we want to round the values so they are easier to read. Go into the R/functions.R
script to the tidy_summarize_by_day()
function. We’ll create a new line right after the dplyr::summarise()
function, after the |>
pipe. Since we want to round values of existing columns, we need to use mutate()
. And like we used across()
in summarise()
, we can also use across()
within mutate()
on specific columns. In our case, we want to round columns that start_with()
the word "value"
to 2 digits.
R/functions.R
tidy_summarise_by_day <- function(data) {
daily_summary <- data |>
dplyr::select(-samples) |>
tidyr::pivot_longer(c(-user_id, -day, -gender)) |>
tidyr::drop_na(day, gender) |>
dplyr::group_by(gender, day, name) |>
dplyr::summarise(
dplyr::across(
value,
list(
mean = \(x) mean(x, na.rm = TRUE),
sd = \(x) sd(x, na.rm = TRUE)
)
),
.groups = "drop"
) |>
dplyr::mutate(dplyr::across(
dplyr::starts_with("value"),
\(x) round(x, digits = 2)
)) |>
tidyr::pivot_wider(
names_from = day,
values_from = dplyr::starts_with("value")
)
return(daily_summary)
}
Source the R/functions.R
file with Ctrl-Shift-SCtrl-Shift-S or with the Palette (Ctrl-Shift-PCtrl-Shift-P, then type “source”), then test out the function in the Console:
#> # A tibble: 9 × 6
#> gender name value_mean_1 value_mean_2 value_sd_1 value_sd_2
#> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 M age 26.0 26.0 7.28 7.28
#> 2 M cortisol_n… 0.03 0.07 0.03 0.05
#> 3 M height 180. 180. 8.34 8.34
#> 4 M hr_mean 81.0 66.9 7.65 6.77
#> 5 M hr_sd 12.7 15.5 4.95 7.03
#> 6 M ibi_s_mean 0.76 0.92 0.08 0.09
#> 7 M ibi_s_sd 0.18 0.28 0.09 0.13
#> 8 M melatonin_… 0 0 0 0
#> 9 M weight 75.3 75.3 13.0 13.0
That’s much easier to read with the values rounded. Now let’s add the ability to change the summary statistics function to something else. This is a surprisingly easy thing so before we do that, let’s take a few minutes to brainstorm how we can achieve this.
Now that we’ve discussed this and come to a conclusion, let’s update the function.
R/functions.R
tidy_summarise_by_day <- function(data, summary_fn) {
daily_summary <- data |>
dplyr::select(-samples) |>
tidyr::pivot_longer(c(-user_id, -day, -gender)) |>
tidyr::drop_na(day, gender) |>
dplyr::group_by(gender, day, name) |>
dplyr::summarise(
dplyr::across(
value,
summary_fn
),
.groups = "drop"
) |>
dplyr::mutate(dplyr::across(
dplyr::starts_with("value"),
\(x) round(x, digits = 2)
)) |>
tidyr::pivot_wider(
names_from = day,
values_from = dplyr::starts_with("value")
)
return(daily_summary)
}
Source the R/functions.R
file with Ctrl-Shift-SCtrl-Shift-S or with the Palette (Ctrl-Shift-PCtrl-Shift-P, then type “source”), then test out the function in the Console:
#> # A tibble: 9 × 4
#> gender name `1` `2`
#> <chr> <chr> <dbl> <dbl>
#> 1 M age 40 40
#> 2 M cortisol_norm 0.16 0.26
#> 3 M height 205 205
#> 4 M hr_mean 97.5 83.1
#> 5 M hr_sd 31.9 38.6
#> 6 M ibi_s_mean 0.96 1.06
#> 7 M ibi_s_sd 0.44 0.56
#> 8 M melatonin_norm 0 0
#> 9 M weight 115 115
Now that it works, let’s add some summary statistics to the doc/learning.qmd
file.
#> # A tibble: 9 × 4
#> gender name `1` `2`
#> <chr> <chr> <dbl> <dbl>
#> 1 M age 27 27
#> 2 M cortisol_norm 0.02 0.06
#> 3 M height 180 180
#> 4 M hr_mean 79.3 66.4
#> 5 M hr_sd 12.1 14.3
#> 6 M ibi_s_mean 0.77 0.91
#> 7 M ibi_s_sd 0.15 0.21
#> 8 M melatonin_norm 0 0
#> 9 M weight 70 70
mmash |>
tidy_summarise_by_day(list(
median = \(x) median(x, na.rm = TRUE),
max = \(x) max(x, na.rm = TRUE)
))
#> # A tibble: 9 × 6
#> gender name value_median_1 value_median_2 value_max_1 value_max_2
#> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 M age 27 27 40 40
#> 2 M cort… 0.02 0.06 0.16 0.26
#> 3 M heig… 180 180 205 205
#> 4 M hr_m… 79.3 66.4 97.5 83.1
#> 5 M hr_sd 12.1 14.3 31.9 38.6
#> 6 M ibi_… 0.77 0.91 0.96 1.06
#> 7 M ibi_… 0.15 0.21 0.44 0.56
#> 8 M mela… 0 0 0 0
#> 9 M weig… 70 70 115 115
While everything now works, the column names are not very clear. For example, what does value_median_1
or 1
mean? It would be nice if it said something like median_day_1
or day_1
. And with pivot_wider()
, we can do that with the name_glue
argument! With this argument, we can write a custom variable naming scheme that involves combining the use of {}
and a special {.value}
keyword within a string in the argument to create these custom column names in the wider dataset. So this would look like {.value}_day_{day}
, where {.value}
refers to the values of the column(s) used in values_from
and the {day}
refers to the column used in names_from
.
We can then pipe the output to rename_with()
from the dplyr package, which acts like map()
(but for renaming columns) and can take an anonymous function. We can use this to then remove the value_
from the start of the column name.
R/functions.R
tidy_summarise_by_day <- function(data, summary_fn) {
daily_summary <- data |>
dplyr::select(-samples) |>
tidyr::pivot_longer(c(-user_id, -day, -gender)) |>
tidyr::drop_na(day, gender) |>
dplyr::group_by(gender, day, name) |>
dplyr::summarise(
dplyr::across(
value,
summary_fn
),
.groups = "drop"
) |>
dplyr::mutate(dplyr::across(
dplyr::starts_with("value"),
\(x) round(x, digits = 2)
)) |>
tidyr::pivot_wider(
names_from = day,
values_from = dplyr::starts_with("value"),
names_glue = "{.value}_day_{day}"
) |>
dplyr::rename_with(\(x) stringr::str_remove(x, "value_"))
return(daily_summary)
}
Let’s see how it looks by rendering the doc/learning.qmd
file again with Ctrl-Shift-KCtrl-Shift-K or with the Palette (Ctrl-Shift-PCtrl-Shift-P, then type “render”). One of the output tables show now look something like:
#> # A tibble: 9 × 6
#> gender name median_day_1 median_day_2 max_day_1 max_day_2
#> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 M age 27 27 40 40
#> 2 M cortisol_norm 0.02 0.06 0.16 0.26
#> 3 M height 180 180 205 205
#> 4 M hr_mean 79.3 66.4 97.5 83.1
#> 5 M hr_sd 12.1 14.3 31.9 38.6
#> 6 M ibi_s_mean 0.77 0.91 0.96 1.06
#> 7 M ibi_s_sd 0.15 0.21 0.44 0.56
#> 8 M melatonin_no… 0 0 0 0
#> 9 M weight 70 70 115 115
Nice!! 😁 🎉
9.8 Making prettier output in Quarto
What we created is nice and all, but since we are working in a Quarto document and generating to HTML, let’s make it easier for others (including yourself) to read the document. Let’s make the output as an actual table. We can do that with knitr::kable()
(meaning “knitr table”). We can also add a table caption with the caption
argument.
doc/learning.qmd
gender | name | mean_day_1 | mean_day_2 | min_day_1 | min_day_2 | max_day_1 | max_day_2 |
---|---|---|---|---|---|---|---|
M | age | 25.95 | 25.95 | 0.00 | 0.00 | 40.00 | 40.00 |
M | cortisol_norm | 0.03 | 0.07 | 0.01 | 0.02 | 0.16 | 0.26 |
M | height | 180.14 | 180.14 | 169.00 | 169.00 | 205.00 | 205.00 |
M | hr_mean | 80.96 | 66.89 | 70.27 | 56.84 | 97.47 | 83.10 |
M | hr_sd | 12.70 | 15.49 | 7.85 | 7.64 | 31.86 | 38.61 |
M | ibi_s_mean | 0.76 | 0.92 | 0.62 | 0.75 | 0.96 | 1.06 |
M | ibi_s_sd | 0.18 | 0.28 | 0.09 | 0.15 | 0.44 | 0.56 |
M | melatonin_norm | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 |
M | weight | 75.29 | 75.29 | 60.00 | 60.00 | 115.00 | 115.00 |
Then render the document with Ctrl-Shift-KCtrl-Shift-K or with the Palette (Ctrl-Shift-PCtrl-Shift-P, then type “render”) and check out the HTML file. So pretty! 😁 Well, there’s lots of things to fix up, but its a good starting place. Let’s finish by running styler with the Palette (Ctrl-Shift-PCtrl-Shift-P, then type “style file”) and then committing the changes to the Git history with Ctrl-Alt-MCtrl-Alt-M or with the Palette (Ctrl-Shift-PCtrl-Shift-P, then type “commit”).
9.9 Summary
- Data is usually structured to varying degrees as wide or long format.
- Use
pivot_longer()
to convert from wide to long. - Use
pivot_wider()
to convert from long to wide.
- Use