4. Recap
Putting it all together
Our question was: Who are Canada’s most dedicated volunteers?
We can answer it with one pipeline that uses functions from both the rows and columns sections:
top_10 <- sgvp |>
filter(volunteer == "Volunteer") |> # keep volunteers
mutate(hours_per_week = volunteer_hours / 52) |> # add hours per week
slice_max(hours_per_week, n = 10) |> # keep the top 10
select(province, age_group, gender, hours_per_week) |> # keep key columns
rename(weekly_hours = hours_per_week) # tidy the name
Look at top_10. What do the most dedicated volunteers have in common?
Practice
Change the pipeline to find the 10 people who donated the most. Show their province, age group, gender, and how much they donated per month.
Click here for solution
top_donors <- sgvp |> filter(donor == "Giver") |> mutate(monthly_donation = donation_amount / 12) |> slice_max(monthly_donation, n = 10) |> select(province, age_group, gender, monthly_donation)
This workshop covered:
Manipulating rows
filter(): keep rows that meet a conditiondistinct(): see the unique values in a columnslice(),slice_max(): pick rows by position or by the largest valuesarrange(): sort rowsbind_rows(): stack data frames on top of each other
Manipulating columns
select(),pull(): keep columns, or take one out as a vectorrelocate(): change the order of columnsrename(): change column namesmutate(),transmute(): add new columns, including withif_else()andcase_when()
And how to combine multiple manipulations with the pipe |>.
Now you are equipped to do basic data manipulation tasks in R with dplyr.
Topics for further learning:
- summarising data with
group_by()andsummarise(), and combining tables with joins (see the bonus sections in the R script), - the comparison of the functions from dplyr package and similar functions from the base R package, such as some shown in STAT 545,
- optional arguments in each function that help control certain features,
- various kinds of functions to use with
mutate()andsummarise(), such as some shown in the dplyr Cheat Sheet, - manipulate multiple variables at once, such as some shown in the dplyr Cheat Sheet.
Practice and use additional resources to build your skill to the next level. You can also attend other workshops or book a consultation with the research commons.
Resources
- Workshops
- Book a consultation
- vignette(“dplyr”)
- Chapter 4 Data transformation in the book R for Data Science (2e) by Hadley Wickham, Mine Çetinkaya-Rundel and Garrett Grolemund
- Chapter 6 Introduction to dplyr in the textbook for STAT 545 by Jenny Bryan and The STAT 545 TAs
- UBC Library workshop: Relational data in R (for more on joins)
Loading last updated date...