Introduction to R
  • Schedule
  • Syllabus
  • Instructors
  • Practice
  • Project
  • Resources

On this page

  • Overview
  • Directions
  • Questions
    • Question 1: Data transformation: Lengthening data
    • Question 2: Data transformation: Widening data
    • Question 3: Putting pivoting together with earlier tools
    • Question 4: Quarto revisited: reporting your results
  • Submission Checklist
  • Note on AI usage

Practice 7

PUBH 523/623

Author

Your name here

Modified

August 11, 2026

Overview

This practice moves from analyzing a single, wide dataset to reshaping data between long and wide formats — a skill you’ll use constantly once your data doesn’t arrive in the shape you need. You’ll pivot two new HRS-based datasets (different from the ones used in Lessons 28-29) both ways, and do a bit of a “round trip” to check that pivoting undoes itself correctly. Along the way, you’ll also polish how you report your results, using several Quarto tools from Lesson 30 to write up your findings in a cleaner, more professional-looking .qmd. You’ll get a little review of filter(), arrange(), and grouped counts from previous weeks along the way — but the focus this week is on pivoting and on Quarto reporting tools.

Topics covered (Lessons 28-30):

  • Data transformation: Lengthening data
  • Data transformation: Widening data
  • Quarto and .qmd’s: Revisited

Directions

Download this practice .qmd from the course GitHub repository, rename it, and save it in your course folder.

  1. Download practice_07.qmd from GitHub.
  2. Rename the file to Lastname_Firstinitial_Practice_07.qmd (or lastname_firstinitial_practice_07.qmd), replacing with your actual last name and first initial.
  3. Save it inside your practice folder. You may create a practice_07 subfolder if you prefer.
TipHow to use this file
  • The boxes with the yellow stripe explain what to do. Keep these in your submitted file.
  • Do all your work below and outside of the yellow-striped boxes.
    • You will need to create code chunks within this document to run your R code.
  • Please delete the following sections before submitting:
    • Overview
    • Directions
    • Tip boxes (green stripe)
    • Caution boxes / Needed Steps (orange/red stripe)
    • Submission checklist
    • Note on AI usage
ImportantNeeded setup
  • Download two new datasets and place them in your data folder:
    • hrs_wide_risk_factors.rds
    • hrs_wide_activity.rds
  • Load the tidyverse, here, and rio packages, plus scales (for this week’s inline-code formatting) and gtsummary/gt (for Question 3).

Questions

Question 1: Data transformation: Lengthening data

In Lesson 28, we learned that pivot_longer() takes multiple columns and collapses them into two new columns: one holding the old column names, and one holding the values.

Part A: Import “wide” data

WarningTask

Import hrs_wide_risk_factors.rds and assign it to hrs_risk. Use glimpse() (or tibble()) to take a look at the data.

Part B: pivot_longer()

WarningTask

Use pivot_longer() on hrs_risk to collapse the 5 risk-factor columns (smoke_ever through high_cesd) into two new columns: risk_factor (holding the old column names) and response (holding the Yes/No values). Keep id, sex, and age_yr as they are. Assign the result to hrs_01_long.

Use nrow() to confirm your work: how many rows do you now have, and why is that the number you’d expect?

Write your answer here.

NoteNote

Please note that we are lengthening a tidy dataset! Just because we can lengthen something, does not mean we should!

Part C: Check your work

WarningTask

Using hrs_01_long, group by risk_factor and use count() on response to see how many respondents have "Yes" vs. "No" for each risk factor. Assign the result to hrs_02_factor_counts and display it.

Which risk factor has the most "Yes" responses?

Write your answer here.

Question 2: Data transformation: Widening data

In Lesson 29, we learned that pivot_wider() does the opposite of pivot_longer(), it spreads values from one column back out across many new columns.

Part A: When to widen

WarningTask

In 1 sentence, describe a situation where you’d want to widen a dataset instead of lengthening it.

Write your answer here.

Part B: pivot_wider()

WarningTask

Starting from hrs_01_long, use pivot_wider() to spread risk_factor back out into separate columns, filled in with the values from response. Assign the result to hrs_03_wide.

Part C: Round-trip check

WarningTask

Compare the dimensions of hrs_03_wide (using dim()) to the dimensions of the original hrs_risk. Are they the same? In 1-2 sentences, explain why lengthening and then widening again should (or shouldn’t) get you back to where you started.

Write your answer here.

Question 3: Putting pivoting together with earlier tools

Pivoting is most useful when combined with tools from previous weeks. Let’s practice that using a second dataset.

Part A: Lengthen a new dataset

WarningTask

Import hrs_wide_activity.rds and assign it to hrs_activity. Use pivot_longer() to collapse the 2019, 2021, and 2023 columns into two new columns: year and activity_level. Keep id and sex as they are. Assign the result to hrs_04_long_years.

TipTip

Column names that start with a number (like 2019) need backticks around them inside cols =, e.g. `2019`:`2023`.

Part B: Review: filter() and arrange()

WarningTask

Using hrs_04_long_years, filter() to keep only the rows where year is "2023", then arrange() by activity_level in descending order. Assign the result to hrs_05_2023_sorted.

Part C: Review: grouped counts

WarningTask

Using hrs_04_long_years, group by year and use tbl_summary() on activity_level to see how exercise frequency is distributed within each year. Assign the result to hrs_06_year_counts.

Does the distribution of activity_level look like it shifts much across the 3 years?

Write your answer here.

Question 4: Quarto revisited: reporting your results

In Lesson 30, we covered tools for writing polished reports: inline code, LaTeX math, code chunk options, callouts, and tabsets. Let’s use a few of them to report what you found above.

Part A: Inline code

WarningTask

Using hrs_risk (from Question 1), calculate the percent of respondents with drink == "Yes". You can use mean() like the lessons or calculate the proportion using counts. Use percent() (from the scales package) to display the value as a percent. Assign the result to an object called perc_drink.

Then copy and paste this sentence and fill it with the inline code: “Approximately _____ of respondents in the HRS dataset report drinking alcohol.”

Part B: LaTeX math

WarningTask

Using LaTeX display math ($$...$$), write out the formula for a proportion: the number of respondents with a given risk factor (\(n\)), divided by the total number of respondents (\(N\)). Use \(\widehat{p}\) (or similar notation) for the proportion itself.

Part C: Code folding

WarningTask

Take the code chunk you used to create hrs_06_year_counts in Question 3 and turn it into a folded code chunk (code-fold: true), with a code-summary of "Counting exercise frequency by year". Please copy and paste the code chunk under this task and then add the chunk options to it.

TipTip

Code chunk options go inside the same chunk as your code, on lines that start with #|. They don’t create a new chunk.

Part D: Cross-referencing

WarningTask

Give that same code chunk a label: starting with tbl- (for example, tbl-activity-by-year) and a tbl-cap: caption. Then, in a sentence below the chunk, reference the table using @ and your chosen label.

Then copy and paste this sentence and fill it with the table reference: “_________ shows that reports of exercising "Every day" become more common in later years, while reports of "Never" exercising become less common.”

Part E: Callout

WarningTask

Add a callout-note (appearance "minimal") that contains the following text: “This is a warning about exercise frequency trends.”

Part F: Tabset

WarningTask

Create a panel-tabset with two tabs: one labeled “Long format” that displays hrs_01_long (using tibble()), and one labeled “Wide format” that displays hrs_03_wide (using tibble()).

Submission Checklist

If having a checklist helps you stay organized, check off each item below as you complete it. You do not need to submit this checklist.

Note on AI usage

I used GenAI (Claude) to help me draft this practice assignment. It helped me brainstorm ideas for the assignment, and I directed it to help you complete the needed tasks that I showed in the lessons.