- Learn
- Computer Science & IT
- Data Science & AI
- Data Analysis with R
- Transforming Data with dplyr
Transforming Data with dplyr
filter(), filter_out() and arrange(), compute new columns with mutate(), and choose and rename columns with select() and rename(). Condense data into grouped summaries and counts with group_by(), summarize() and count(), and chain every step into a readable pipeline with the pipe |>. Along the way you learn to handle missing values, read grouped results correctly and check each step so the final numbers are right.IntermediateLesson 3 of 7 in Data Analysis with R Course
What you will learn
- Understand the rules that every dplyr verb shares, read the structure of a tibble, and chain verbs into readable pipelines with the pipe
|>.- Understand how dplyr verbs workLoad dplyr, inspect a tibble and its column types, and use the shared rules of the verbs: data first, bare column names, and a new data frame as the result.
- Chain steps with the pipeWrite multi-step transformations as pipelines with
|>, read them as a sequence of steps, lay them out clearly, and know how|>differs from%>%.
- Understand how dplyr verbs work
- Keep or drop rows with logical conditions, sort rows, and pick unique or top rows, while handling missing values deliberately.
- Keep and drop rows with filter()Write conditions with comparison and logical operators, combine them correctly, avoid the classic mistakes, and decide what happens to rows with missing values.
- Sort rows with arrange()Order rows by one or more columns, in ascending or descending order, and predict where missing values and text with capital letters end up.
- Find unique rows and pick rows by position or valueRemove duplicate rows with distinct(), and keep the first, last, largest, smallest or random rows with the slice functions, overall or per group.
- Keep and drop rows with filter()
- Compute new columns with mutate(), including conditional, ranked and running values, and choose, rename and reorder the columns of a table.
- Create and change columns with mutate()Add new columns computed from existing ones, control where they appear and which old columns stay, and compute group-relative values.
- Compute conditional, ranked and running valuesAssign values by condition with if_else() and case_when(), and use window functions such as lag(), cumsum() and min_rank() inside mutate().
- Choose, rename and reorder columnsPick columns by name, range, pattern or type with select(), rename them with rename() and rename_with(), and move them with relocate().
- Create and change columns with mutate()
- Reduce data to summary statistics, compute them per group with group_by() or .by, count rows and values, and judge every summary by the size of its groups.
- Compute summary statistics with summarize()Collapse a data frame into summary values, handle missing values on purpose, and pick summary functions that return one value each.
- Group rows with group_by() and .bySplit data into groups by one or more columns, compute per-group results, control what grouping remains afterward, and choose between group_by() and .by.
- Count rows and valuesCount rows per group with count() and its relatives, weight counts, turn counts into proportions, and tell rows apart from distinct values.
- Judge summaries by group sizeReport counts next to averages, recognize misleading results from small groups, and set a minimum group size before ranking.
- Compute summary statistics with summarize()
- Turn a data question into an ordered sequence of dplyr steps, and check every step so that the final table is correct.
- Plan a pipeline from a questionTranslate a question into the rows, columns and order of the result, choose the verbs and their order, and decide what each summary should measure.
- Check and debug a pipelineRun pipelines step by step, compare each result with the shape you expect, read errors and messages, and cross-check totals and missing values.
- Plan a pipeline from a question
Transforming Data with dplyr study guide
1Work with dplyr verbs and the pipe
A useful transformation starts with knowing what a table contains and what each verb returns. You will inspect a small running log, read its column types, and use column names inside dplyr calls. Then you will join calls with the pipe so that the code reads in the order the work happens. The same table will support later examples, so create it once and keep the original available while you explore.
1.1 Understand how dplyr verbs work
Each row in a data frame records an observation; each column records a variable. dplyr supplies verbs that transform these tables. Load it with library(dplyr), or load library(tidyverse) to attach it along with ggplot2 and the other core tidyverse packages.
Create and inspect the running log
Run this code to create the table used in the examples:
library(dplyr)
runs <- tibble(
runner = c("Ana", "Ben", "Chen", "Ana", "Ben",
"Chen", "Ana", "Ben", "Chen", "Ana"),
week = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 3),
distance_km = c(5, 8, 6.5, 10, 12, NA, 7.5, 4, 9, 5),
time_min = c(30, 44, 39, 62, 70, 41, 45, 26, 54, 31)
)
glimpse(runs)
A tibble is a modern data frame. The print header 10 × 4 means 10 rows and 4 columns. The type under runner is <chr> for character text; the three numeric columns are <dbl> for double-precision numbers. Other common types are <int> for integers and <lgl> for logical values, TRUE and FALSE. A number written without a decimal point can still have type <dbl>. glimpse() displays each column on its own line, making names and types easier to scan.
One row is one run. Ana has two runs in week 3, so a runner-week pair does not uniquely identify a run. Chen's week-2 distance is NA, R's missing-value marker. His time is still recorded. Missing distance does not mean zero distance.
Read a verb call
In filter(runs, week == 2), the first argument supplies the data and the next argument describes the operation. filter() keeps rows; the result has the three week-2 runs and the original four columns. Other main verbs sort rows (arrange()), compute columns (mutate()), choose columns (select()), or reduce rows to summaries (summarize()). A tibble goes in and a new tibble comes out.
Inside filter(), week refers directly to the column. This is data masking: you can compute with a column's values without repeatedly naming its table. A character value still needs quotes:
ana_runs <- filter(runs, runner == "Ana")
Here runner names a column and "Ana" supplies the text to match. Writing "runner" == "Ana" compares two fixed pieces of text. That comparison is false, so it keeps no rows.
Keep a result and identify a function
A verb returns its result without changing its input. filter(runs, week == 2) leaves runs at 10 rows. Assigning the result to week2 saves a separate table; assigning it back to runs replaces that object in your session. Use descriptive result names while exploring so the raw table stays available.
Loading dplyr can report that filter() and lag() mask functions in the stats package. The code has still loaded. A namespace makes the function choice explicit: dplyr::filter() calls dplyr's row filter, while stats::filter() calls a different function with the same name.
Key Takeaways
- Verbs take the data first and return a new table.
- Use bare column names and quoted text values inside data-masking expressions.
- Inspect row counts, column names, types, and missing values before computing.
- Assignment saves a result; a verb call alone leaves its input unchanged.
- Use a package namespace when function names conflict.
1.2 Chain steps with the pipe
A pipeline presents several operations in reading order. The native pipe |> sends the value on its left into the first argument of the function call on its right. Read it as "then."
Follow the data through the calls
The question "Which week-3 runs were longest?" needs a row choice followed by a sort:
week3_longest <- runs |>
filter(week == 3) |>
arrange(desc(distance_km))
Start with 10 runs. filter() leaves four week-3 rows. arrange() keeps those four rows and puts them in descending distance order: Chen 9 km, Ana 7.5 km, Ana 5 km, Ben 4 km. The final result is saved as week3_longest.
The first step means filter(runs, week == 3). The next receives that result as its own first argument. You do not repeat runs inside each call: that would supply the data again where the function expects an operation.
| Form | How the steps are read |
|---|---|
arrange(filter(runs, week == 3), desc(distance_km)) | Find the inner filter, then read the outer sort. |
| Two separately named intermediate tables | Follow the names from one command to the next. |
| A pipeline | Read the data, then each operation from top to bottom. |
Intermediate objects are useful when you want to inspect or reuse a stage. A pipeline is useful when the stages belong to one question.
Lay out a pipeline that runs
Put one verb on each line, indent it, and leave |> at the end of the preceding line. This tells R the command continues. A new line starting with |> cannot attach itself to a command that R has already finished. Place <- before the input table when saving the result.
To check a stage, run the expression through that stage without its trailing pipe. Check the table before adding the next verb. For this example, expect four rows after filtering and the same four after sorting.
Recognize the two pipes
|> belongs to base R from version 4.1.0. %>%, from magrittr, is also available after loading dplyr or the tidyverse. For simple dplyr chains they give the same result. Their syntax differs:
| Feature | Native pipe | magrittr pipe |
|---|---|---|
| Function call | runs |> nrow() | runs %>% nrow() or runs %>% nrow |
| Placeholder | _, once in a named argument | ., including unnamed positions |
For an ordinary call whose data argument comes later, the native placeholder can put the input there: runs |> lm(time_min ~ distance_km, data = _). This illustrates argument placement; dplyr's data-first verbs do not need a placeholder. The named-argument placeholder is available from R 4.2.0. In current R, _ can also head an extraction chain such as _$coef.
End in a plot
A pipeline can prepare the data for ggplot2:
runs |>
filter(!is.na(distance_km)) |>
ggplot(aes(x = distance_km, y = time_min)) +
geom_point()
Load ggplot2 or the tidyverse for this call. Pipes connect data transformations; + adds plot layers. In RStudio, Ctrl+Shift+M, or Cmd+Shift+M on a Mac, inserts a pipe. The "Use native pipe operator" setting under Tools > Global Options > Code chooses which pipe the shortcut inserts.
Key Takeaways
x |> f(y)passesxas the first argument off().- End continued lines with a pipe and save the result with assignment at the start.
- The native pipe needs function-call parentheses;
%>%also permits a bare function name. - Use
+to add ggplot2 layers.
2Choose and order the rows you need
Choosing rows and putting them in order answer different questions. You might want runs from a particular week, the longest run for each person, or one row for every runner. Logical conditions, sorting, and the slice helpers give you those choices. Missing distances and tied values need attention because they affect which rows appear. You will learn to predict the result before relying on the printed table.
2.1 Keep and drop rows with filter()
A row condition produces one logical result for each row. filter() keeps TRUE results and drops FALSE or NA results. It preserves the columns and the order of the rows it keeps.
Build the condition
Use == for equality, != for inequality, and <, <=, > or >= for comparisons. filter(runs, distance_km >= 7) keeps five runs: 8, 10, 12, 7.5, and 9 km. A single = names an argument; filter(runs, week = 2) is an error. The comparison is week == 2.
Combine conditions with & for "and," | for "or," and ! for "not." Commas inside filter() mean "and":
runs |>
filter(runner == "Ben", time_min < 45)
Ben's 44-minute and 26-minute runs satisfy both conditions. For "Ana or Chen," use runner %in% c("Ana", "Chen"). Membership with %in% asks whether each value belongs to the set. between(distance_km, 5, 8) includes both endpoints. With several alternatives, when_any(condition1, condition2) combines them with "or" in dplyr 1.2.0 and later.
& is evaluated before |. Use parentheses to show which alternatives must also satisfy a shared restriction, as in filter(runs, (runner == "Ana" | runner == "Chen") & week == 3).
Avoid two plausible-looking shortcuts
week == 1 | 3 does not test membership in weeks 1 and 3. The number 3 becomes TRUE in the logical operation, so every row passes. Repeat the comparison or use week %in% c(1, 3); the correct result has seven rows.
week == c(1, 3) also fails to express membership. R compares successive rows with 1, 3, 1, 3, and so on. With ten rows this recycles without a warning and happens to keep four rows. A recycled comparison can run successfully while answering the wrong question.
Choose the missing-value behavior
A missing distance cannot be judged equal to, above, or below a recorded number. Its comparison result is NA. This changes a negative filter:
| Call | Result |
|---|---|
filter(runs, distance_km != 5) | Seven rows; the unknown distance is dropped. |
filter_out(runs, distance_km == 5) | Eight rows; the unknown distance stays. |
filter(runs, is.na(distance_km)) | Chen's week-2 row only. |
filter_out() drops rows whose condition is TRUE, retaining FALSE and NA. It and when_any() require dplyr 1.2.0 or later. With the same condition, filter() and filter_out() partition the input: every row appears in exactly one result. To keep the eight rows with filter() alone, use distance_km != 5 | is.na(distance_km).
Do not test distance_km == NA: every result is unknown. is.na() specifically tests for missingness.
Compare with care
Binary storage makes many decimals approximate. In R, 0.1 + 0.2 == 0.3 is false; near(0.1 + 0.2, 0.3) is true because it permits a tiny difference. Whole week numbers can use ordinary equality.
A condition may also compare a row with a calculated summary: filter(runs, distance_km > mean(distance_km, na.rm = TRUE)) keeps the five distances above about 7.44 km. With grouping, that mean is computed separately within each group.
Key Takeaways
filter()keeps true conditions;filter_out()drops true conditions and retains unknown ones.- Commas mean "and"; use
|,when_any(), or%in%for alternatives. - Use
is.na()to find missing values. - Use
==for comparisons and%in%for membership. between()includes both endpoints.- Use
near()when tiny decimal-storage differences should count as equal.
2.2 Sort rows with arrange()
Sorting makes patterns and extreme values easier to see. arrange() changes row order, keeping all rows, all columns, and the values within each row together.
Choose the direction and tie breakers
The default is ascending: small numbers first, early dates first, and text in the default text order. desc() reverses the order of one column:
runs |> arrange(desc(distance_km))
The first distances are 12, 10, and 9 km. The last recorded distance is 4 km, followed by the missing distance. Sorting a distance does not detach it from its runner or time: the entire row moves.
With several sort columns, the first is the main key and each later column breaks ties left by earlier keys:
runs |> arrange(runner, desc(time_min))
This starts with Ana's runs, ordered 62, 45, 31, and 30 minutes. Ben's runs follow in 70, 44, and 26-minute order, then Chen's in 54, 41, and 39-minute order. desc() affects time_min only; runner names remain in ascending order.
Put missing values where you need them
For these local data frames, arrange() puts missing values last in both directions. Reversing a numeric sort does not move NA to the top. To inspect missing rows first, make missingness the first sort key:
runs |>
arrange(desc(is.na(distance_km)), distance_km)
is.na() is true for Chen's week-2 row. Descending logical order puts true before false. The second key orders the recorded distances from shortest to longest. This is useful when checking whether rows with incomplete measurements also have unusual times.
Understand text order
Current dplyr uses the C locale by default. For basic Latin letters, uppercase letters precede lowercase letters. If fruits has a name column containing "apple," "Banana," and "cherry," arrange(fruits, name) starts with "Banana."
For English dictionary ordering, use arrange(fruits, name, .locale = "en"); the order becomes "apple," "Banana," "cherry." This option needs stringi installed. Default C ordering gives a consistent result across computers, while an explicit locale gives the language-specific order you choose.
Sort at the stage that matters
Sorting does not select the top rows. To keep the three longest runs, use slice_max(distance_km, n = 3) or sort descending and then use slice_head(n = 3). A later grouped summary can establish a different order, so sort the final summary when the report needs a ranking.
Persistent grouping also does not make arrange() sort each group as a separate block automatically. Add .by_group = TRUE to sort by the grouping columns first, then the named sort columns. If you already name runner first, arrange(runner, week) makes that grouping order explicit.
Sorting the smallest and largest values is a quick quality check. A negative distance or a zero-minute run should prompt a look at the recorded row before you build a pace column from it.
Key Takeaways
- Use
desc()on each column that needs descending order. - Later sort columns break ties in earlier columns.
- Missing values sort last in either direction on local data frames.
- Sort the final summary when its display order matters.
- Text order depends on the locale; C ordering places uppercase Latin letters before lowercase ones.
2.3 Find unique rows and pick rows by position or value
Choosing one row per runner, choosing the longest run, and choosing the first recorded run are different tasks. distinct() works with unique values; the slice family works with positions, extremes, or random choices.
Keep unique combinations
distinct(runs) compares every column and removes completely duplicated rows. The log has no identical rows, so all ten remain. Naming columns changes what counts as a match:
runs |> distinct(runner, week)
There are nine runner-week combinations because Ana appears twice in week 3. The result contains only runner and week. distinct(runs, runner, .keep_all = TRUE) keeps all columns but keeps only the first row seen for each runner: each person's week-1 run. That first row is not necessarily their longest or latest run. count() gives frequencies when you need to know how often a combination occurs.
Pick positions or a share
slice_head(n = 3) keeps the first three rows in the current order; slice_tail(n = 3) keeps the last three. slice(runs, 2:4) keeps positions 2 through 4. Negative positions remove rows: slice(runs, -1) removes the first row. Repeated positive positions can duplicate rows, so slice(runs, c(1, 1)) returns the first row twice.
Positions describe the table as it exists at that moment. A preceding filter or sort changes them. For a value-based task such as "the longest runs," choose a value-based helper or sort first.
slice_head(runs, prop = 0.5) keeps half the rows, here five. For a positive proportion producing a fraction of a row, the count rounds down. Asking for more rows than are available simply returns the available rows.
Choose extremes and decide about ties
runs |>
slice_min(distance_km, n = 1, by = runner)
Ana's shortest distance is 5 km, and it occurs twice. Both rows are kept. Ben contributes his 4 km row and Chen his 6.5 km row, giving four rows altogether. with_ties = FALSE keeps one row per runner in this example, breaking equal values by their existing order.
slice_max(distance_km, n = 2) keeps the 12 km and 10 km runs. Missing distances are placed last and can be included if too few recorded values are available; na_rm = TRUE excludes them. The argument has an underscore, unlike na.rm inside sum().
The helper functions slice_head(), slice_tail(), slice_min(), slice_max(), and slice_sample() use by for one-operation grouping. The general slice() function uses .by, as do filter(), mutate(), and summarize().
Take a reproducible random sample
set.seed(42)
runs |> slice_sample(n = 3)
The seed makes repeated runs of the same sampling code reproducible in the same setup. Sampling is without replacement by default, so a row is selected at most once. replace = TRUE permits repeat selections. A random sample serves a different purpose from taking the first three rows, which depends entirely on how the log was ordered.
Key Takeaways
distinct()keeps unique rows or named combinations..keep_all = TRUEretains other columns from the first matching row.- Use positions for position-based tasks and extreme-value helpers for largest or smallest values.
- Ties can make
slice_min()orslice_max()return more rows than requested. - Slice helpers use
by;slice()uses.by. - Set a seed before a reproducible random sample.
3Create and organize columns
New columns turn recorded values into quantities you can compare: pace, speed, changes, or labels. Some calculations work within a row; others depend on a group or on the order of nearby rows. You will build each kind with mutate(), then choose clear names and a readable column order. Keeping track of units and missing values makes these derived columns useful in the summaries that follow.
3.1 Create and change columns with mutate()
mutate() creates or changes columns while retaining the number of rows. Calculations usually run element by element: the distance and time in one row produce the pace for that same run.
Compute with units
runs |>
mutate(pace_min_per_km = time_min / distance_km)
Ana's first pace is 30 minutes divided by 5 km, or 6 min/km. Ben's first is 44 divided by 8, or 5.5 min/km. A smaller pace means less time per kilometer. Chen's unknown distance produces NA; there is no known pace for that row.
A single value is repeated down the whole column: mutate(runs, device = "watch") adds that text to each of the ten rows. Several columns can be created in one call, and a later expression can use an earlier one:
runs |>
mutate(
hours = time_min / 60,
speed_kmh = distance_km / hours
)
Ana's first run takes 0.5 hours and covers 5 km, so its speed is 10 km/h. The conversion is needed because kilometers divided by minutes would give kilometers per minute. A name that includes the unit helps the next reader check the expression.
Control the columns you see
New columns normally appear at the right. Place one beside its inputs with .after = runner or make it first with .before = 1. An existing column that you replace keeps its position.
.keep chooses which old columns remain:
| Value | Existing columns retained |
|---|---|
"all" | All of them; the default. |
"used" | Columns used in the expressions. |
"unused" | Columns not used in the expressions. |
"none" | Only grouping columns, alongside the created columns. |
For example, mutate(runs, pace = time_min / distance_km, .keep = "used") shows distance_km, time_min, and pace. Seeing the inputs beside the output makes a mistaken division easier to spot.
Using an old name replaces its values. mutate(runs, time_min = time_min * 60) puts seconds in a column whose name still claims minutes. Create time_s instead. Assigning NULL removes a column, as in mutate(runs, time_min = NULL).
Use the correct assignment sign
Inside mutate(), write pace = time_min / distance_km. The outer <- saves a whole result table. Using <- inside the verb does not give the intended column the name pace; dplyr derives a name from the expression. Calling mutate() without an outer assignment also leaves runs unchanged.
Make a calculation relative to a group
runs |>
mutate(
share = distance_km / sum(distance_km, na.rm = TRUE),
.by = runner
)
Each runner supplies a separate denominator. Ana's 10 km run has share about 0.364 of her 27.5 km; Ben's 12 km run has share 0.5 of his 24 km. Without .by, every recorded distance is divided by the overall 67 km. Both versions retain all ten rows. Grouping changes the scope of the calculation, while mutate() still attaches results to individual runs.
Key Takeaways
mutate()preserves the row count and computes new or replacement columns.- Later expressions in one call can use columns created earlier.
- Keep units consistent with the expression and column name.
- Use
.keepto inspect inputs alongside outputs. - Group-relative calculations use a separate summary within each group.
3.2 Compute conditional, ranked and running values
A derived column can depend on a condition, a neighboring row, or a row's rank.
Choose values by condition
if_else(condition, true, false) has two outcomes. This labels recorded distances as "long" or "short":
runs |>
mutate(type = if_else(distance_km >= 8, "long", "short",
missing = "unknown"))
Four runs are long, five are short, and the missing distance is unknown. Without missing, that label would be NA. The two outcome values must have compatible types: "long" and 0 cannot form one column with if_else().
For several outcomes, case_when() checks condition ~ value pairs in order. Each row takes its first true match:
runs |>
mutate(
pace = time_min / distance_km,
effort = case_when(
is.na(pace) ~ "unknown",
pace < 5.9 ~ "fast",
pace < 6.3 ~ "steady",
.default = "easy"
)
)
This gives two fast, six steady, one easy, and one unknown run. Putting pace < 6.3 first would also catch every fast pace, so the later fast branch would never win. A missing comparison is not a match; the explicit is.na() branch stops an unknown pace from falling into "easy." Without .default, an unmatched row gets NA.
Calculate a change from the previous row
lag(x) returns the previous value and lead(x) the next. Subtract the lag to measure a change:
runs |>
arrange(runner, week) |>
mutate(change_km = distance_km - lag(distance_km),
.by = runner)
Ben's distances are 8, 12, and 4 km. His changes are NA, 4, and -8 km. The first run has no earlier run. Grouping prevents the first run for Ben from being compared with the last run for Ana. Sorting establishes week order; when multiple runs share a week, a finer time or sequence column is needed if their within-week order matters.
Accumulate in order
cumsum() builds a running total, cummean() a running mean, and cummin() or cummax() a running extreme. With the log's existing week order, mutate(runs, km_so_far = cumsum(distance_km), .by = runner) gives Ana 5, 15, 22.5, and 27.5 km. Chen gets 6.5, NA, and NA: an unknown contribution makes that total and later totals unknown. Replacing it with zero would assert that no distance was added.
Rank values and handle ties
min_rank(desc(distance_km)) gives the longest run rank 1. Equal distances share a rank, and later ranks skip positions: the two 5 km runs have rank 7, followed by the 4 km run at rank 9. dense_rank() shares ranks without gaps; row_number() gives different numbers, breaking ties by current row order. Missing values get rank NA.
Key Takeaways
if_else()chooses two compatible outcomes and can name a missing outcome.case_when()takes the first true match, so condition order matters.- Catch missing values explicitly when a default label would be misleading.
- Sort and group before calculating changes or cumulative values.
min_rank()leaves gaps after ties;dense_rank()does not.- A missing contribution makes later ordinary cumulative totals unknown.
3.3 Choose, rename and reorder columns
A readable result table shows the columns needed to answer the question, with names and positions that make their meaning clear. Column selection, renaming, and moving have different effects.
Select names and patterns
select(runs, runner, distance_km) keeps two columns in that order and all ten rows. week:time_min selects neighboring columns from week through time_min. !week, or -week, excludes that column.
Helpers pick sets of column names:
| Helper | Example selection |
|---|---|
starts_with("dist") | Names starting with "dist." |
ends_with("_min") | Names ending with "_min." |
contains("time") | Names containing "time." |
matches("^q[12]_") | Names matching a regular expression. |
num_range("q", 1:3) | Names q1, q2, q3. |
where(is.numeric) | Numeric columns. |
everything() means all remaining columns; last_col() means the last column. Helpers can be combined with &, |, and !. If survey contains id, q1_text, q1_score, q2_text, and q2_score, then select(survey, starts_with("q1") & !ends_with("_text")) keeps only q1_score.
Select names stored as text
A vector of required names needs all_of() or any_of():
cols <- c("runner", "pace")
runs |> select(any_of(cols))
Only runner exists, so any_of() keeps it and skips pace. all_of(cols) stops with an error because pace is missing. Use that strict check when a missing column means the analysis cannot proceed correctly. Use any_of() when skipping absent names is intended.
Rename or move without losing columns
runs |> rename(km = distance_km)
runs |> relocate(time_min, .before = week)
rename() uses new_name = old_name: it finds distance_km and calls it km, keeping the other columns in place. Reversing those names makes it search for a column named km. rename_with(runs, toupper) applies a function to every selected name, producing uppercase names.
select() can rename while choosing: select(runs, name = runner, km = distance_km) returns just two columns. If you only meant to change a name, this would silently lose week and time_min.
relocate() moves columns while keeping them all. Its default destination is the front. .before = week puts time_min just before week; .after = last_col() moves a chosen column to the end.
Distinguish names from values
These helpers use tidy selection, a language for choosing columns by name, position, pattern, or type. .by also selects grouping columns this way. Data masking in filter(), mutate(), and summarize() computes with the values inside columns. starts_with("d") therefore belongs in select(); it does not produce a per-row condition for filter().
On a persistently grouped table, select() keeps grouping columns even when you leave them out and reports that it added them. If a result unexpectedly retains runner, inspect its grouping before changing the selection.
Key Takeaways
select()keeps named columns in the requested order.- Helpers choose columns by name pattern, position, or type.
all_of()requires every stored name;any_of()skips missing names.rename()usesnew = oldand preserves other columns.relocate()changes column order without dropping columns.- Tidy selection chooses columns; data masking computes with their values.
- Grouping columns remain available after
select().
4Summarize data by groups
A summary changes what one row represents. Ten runs can become three runner totals or nine runner-by-week totals. You will choose summary functions, define groups, and control whether grouping carries into later work. Counts also show how much information supports a mean. Reading the count beside the average helps you recognize a result that rests on very few recorded values.
4.1 Compute summary statistics with summarize()
A summary reduces many observations to a smaller table. With ungrouped data, summarize() returns one row. Each expression names a summary column and must produce one value.
Summarize the log
runs |>
summarize(
total_km = sum(distance_km, na.rm = TRUE),
mean_km = mean(distance_km, na.rm = TRUE),
n_runs = n(),
n_recorded = sum(!is.na(distance_km))
)
The result has total distance 67 km, mean distance about 7.44 km, ten runs, and nine recorded distances. n() counts rows, including the row with a missing distance. It takes no arguments and works inside dplyr verbs. sum(!is.na(distance_km)) counts only recorded distances because true logical values count as 1 and false values as 0.
Pick the statistic that answers the question
| Purpose | Functions |
|---|---|
| Total or center | sum(), mean(), median() |
| Spread | sd(), IQR() |
| Smallest or largest | min(), max() |
| Value at a position | first(), last(), nth() |
| Rows or different values | n(), n_distinct() |
Position-based summaries refer to current row order. first(distance_km) does not automatically mean the smallest distance.
The nine recorded distances have median 7.5 km and mean about 7.44 km. If the 12 km entry were mistyped as 120 km, the mean would rise to about 19.44 km while the median stayed at 7.5 km. Comparing center measures can help reveal an unusual entry, although you still need to inspect the actual data.
Handle missing values and denominators
sum(distance_km) returns NA because one contribution is unknown. na.rm = TRUE excludes missing values for that function call. It does not fill them in or remove their rows from other calculations. The 67 km is a total of recorded distances.
Logical summaries are useful for counts and shares:
runs |>
summarize(
long_runs = sum(distance_km >= 8, na.rm = TRUE),
share_long = mean(distance_km >= 8, na.rm = TRUE)
)
Four recorded runs reach 8 km. The proportion is four out of nine recorded distances, about 0.44. Dividing by n() would instead use all ten runs, treating the missing distance as part of a different denominator. Report the population your fraction describes.
Later expressions can use earlier summary columns on a local data frame: summarize(runs, total = sum(distance_km, na.rm = TRUE), used = sum(!is.na(distance_km)), mean_km = total / used). Distinct names keep the original columns available while calculating.
Choose the output shape
mutate(runs, mean_km = mean(distance_km, na.rm = TRUE)) repeats the mean beside all ten runs. summarize() returns it once. Current dplyr requires one value per group from each summary expression. range() produces a minimum and maximum, so use reframe(runs, km = range(distance_km, na.rm = TRUE)) for two rows, 4 and 12, or use separate min() and max() columns in a summary.
Key Takeaways
- Each
summarize()expression returns one value per group. na.rm = TRUEexcludes missing values for that calculation only.n()counts rows; a non-missing count measures recorded observations.- A logical sum counts true results and a logical mean gives their share.
- Use
reframe()for expressions that return several rows per group.
4.2 Group rows with group_by() and .by
Grouping defines which rows a calculation sees together. A runner total uses one group per person; a weekly runner total uses one group per person-week combination. The data rows stay intact until a verb changes them.
Create groups and summarize
runs |>
group_by(runner) |>
summarize(total_km = sum(distance_km, na.rm = TRUE),
n_runs = n())
The grouped input has a # Groups: line naming runner. The summary has three rows: Ana 27.5 km in four runs, Ben 24 km in three, and Chen 15.5 km in three. group_by() sorts group keys for summary output; character keys use C-locale ordering.
group_by(runner, week) defines nine observed combinations. Ana's two week-3 rows are one group. summarize(km = sum(distance_km)) returns nine rows, including Ana's 12.5 km week and Chen's unknown week-2 total. Each grouping column appears beside the summary columns.
Decide what grouping survives
A grouped summary removes the last grouping level by default. From group_by(runner, week), the output stays grouped by runner. A message reports the remaining grouping; it is information about completed work, not a failed command.
.groups value | Result |
|---|---|
"drop_last" | Remove the last grouping level; default for grouped data. |
"drop" | Remove all grouping. |
"keep" | Keep all grouping levels. |
With one grouping column, removing the last level leaves ungrouped data. With several, specify .groups = "drop" when later calculations should see the entire result.
This affects a share column. After weekly runner totals, a still-grouped mutate(share = km / sum(km, na.rm = TRUE)) divides by each runner's total. Ana's week 3 is about 0.45 of her distance. Ungrouping first makes its denominator the overall 67 km, giving about 0.19. Both results can look reasonable; they answer different questions.
ungroup() removes persistent groups. Grouping otherwise survives ordinary filter(), mutate(), and arrange() calls and stays attached when you save the table. Inspect it with group_vars().
Group for one operation
runs |>
summarize(total_km = sum(distance_km, na.rm = TRUE),
n_runs = n(), .by = runner)
.by supplies groups only for this verb and returns ungrouped data. For several keys, use .by = c(runner, week). Its summaries retain the groups' first-appearance order. Add arrange() if the output needs a particular sort. You cannot supply .by to a table already grouped with group_by(); ungroup it first.
Apply group scope beyond summaries
filter(runs, distance_km == max(distance_km, na.rm = TRUE), .by = runner) keeps each person's longest run: 10, 12, and 9 km. Without grouping it would compare everyone with the single overall maximum.
group_by() can create groups from an expression, such as long = distance_km >= 8. The log then has five false rows, four true rows, and one missing-value group. .by selects existing columns, so create a calculated grouping column with mutate() first when using that route.
Key Takeaways
- Grouping changes the scope of calculations without itself collapsing rows.
- Multiple keys form groups from observed combinations.
- A grouped summary drops the last grouping level by default.
- Use
.groups = "drop"orungroup()before whole-table calculations. .bygroups one operation and preserves first-appearance group order.- Use
.byon ungrouped input.
4.3 Count rows and values
Counting helps you see how many observations belong to each category and how much data supports later calculations. Decide whether you need a count of rows, a count of different values, or a total of a numeric column.
Count categories and combinations
runs |> count(runner)
The result contains Ana 4, Ben 3, and Chen 3 in a column named n. count(runner, week) counts combinations, so it returns nine rows; Ana's week-3 combination has n = 2. Combinations absent from the data do not appear. For factor columns, .drop = FALSE can include unused levels with zero counts.
sort = TRUE puts the largest counts first. count(runs, week, sort = TRUE, name = "n_runs") starts with week 3 at four runs, followed by weeks 1 and 2 at three each. The name argument makes the measure explicit in a report.
count() groups temporarily. Its output keeps the input's persistent grouping; an ungrouped input produces ungrouped counts. If the input was already grouped, inspect that state before computing shares from its counts.
Add counts without collapsing rows
runs |>
add_count(runner, name = "runner_n") |>
filter(runner_n >= 4)
add_count() first keeps all ten rows and writes each runner's group size beside every run. The filter then keeps Ana's four rows. By comparison, count() would give only one summary row per runner. tally() counts using grouping that already exists: runs |> group_by(week) |> tally() gives weekly counts of 3, 3, and 4.
Weight a count
count(runs, runner, wt = distance_km) adds distances instead of counting runs. It returns Ana 27.5, Ben 24, and Chen 15.5. Weighted count() skips missing weights, equivalent here to sum(distance_km, na.rm = TRUE). A plain sum(distance_km) in summarize() would leave Chen's total unknown. Use name = "total_km" so a weighted total is not mistaken for a row count.
Turn counts into proportions
runs |>
count(week) |>
mutate(prop = n / sum(n))
The ungrouped counts sum to ten, so weeks 1, 2, and 3 have shares 0.3, 0.3, and 0.4. The denominator is the total of the count column in this result. Leftover grouping would change its scope.
Count observations and distinct people separately
runs |>
summarize(
n_runs = n(),
n_runners = n_distinct(runner),
recorded = sum(!is.na(distance_km)),
.by = week
)
Week 3 has four runs by three people. Repeated observations are real rows, but they do not create extra people. Week 2 has three runs and only two recorded distances. Showing both counts prevents a later distance mean from appearing to use all three rows.
Category counts also reveal possible data errors. Text values "Ana" and "ana" count separately. An unexpected one-row category or an unusually large count is a reason to inspect its underlying rows before interpreting its average.
Key Takeaways
count()collapses rows to group counts;add_count()keeps rows and adds their group count.wtturns a count into a total and skips missing weights.n()counts rows;n_distinct()counts different values.- Compute proportions using a denominator with the intended grouping.
- Use counts to check category spelling and the amount of recorded data.
4.4 Judge summaries by group size
An average describes the values used to calculate it. Its usefulness also depends on how many observations support it. A ranking without counts hides that part of the evidence.
Read a mean beside its count
Suppose a café summary lists Nova at 5.0 stars from two ratings, Lumen at 4.6 from 180, and Oak at 4.4 from 95. Nova has the highest observed mean, but that position rests on only two opinions. A single new rating can move it substantially. For Lumen, one additional rating has much less influence on the mean.
A small group can have an ordinary average too. The issue is greater variability: a few unusually high or low observations can push its mean far from its typical level. Small groups therefore appear at the extremes of rankings more often than their underlying level justifies. Counts do not prove that any particular mean is wrong or that the largest group must rank first.
Apply and report a minimum size
reviews |>
summarize(avg = mean(stars), n = n(), .by = cafe) |>
filter(n >= 20) |>
arrange(desc(avg))
For the café data described here, all star values are recorded. The size rule keeps Lumen and Oak and excludes Nova before ranking. The final report should say that it includes cafés with at least 20 ratings. Twenty is the chosen reporting rule for this example, not a universal guarantee that an average is dependable.
Filtering raw rows on their star value would change the average itself. Filtering the completed summary on n instead decides which whole cafés enter the comparison. Keep those two decisions separate when planning a report.
Count the values actually used
If some values are missing, n() can overstate the support for the mean. In the running log, Chen has three rows but only two recorded distances. His recorded-distance mean is 7.75 km:
runs |>
summarize(
mean_km = mean(distance_km, na.rm = TRUE),
n_runs = n(),
n_recorded = sum(!is.na(distance_km)),
.by = runner
)
His n_runs is 3 and n_recorded is 2. A minimum-size rule for that distance mean should be applied to the count of recorded distances. A row with unknown distance still counts as a run, but it cannot contribute a distance to the mean.
Inspect unusual group sizes
Averages plotted against group size often show a wider spread among the smallest groups. That view can help you see how the ranking depends on limited data. It does not replace checking how observations were collected.
An unexpected count also suggests a data check. A category with one row may be a misspelled name; a very large group may contain repeated records. Examine the rows before removing them: Ana's two week-3 runs are legitimate separate observations. distinct(runner, week) would collapse them because it defines uniqueness more broadly than a complete run record.
Key Takeaways
- Report counts beside group averages.
- Small-group means can move substantially when one new value is added.
- Apply a stated minimum size before ranking eligible groups.
- When a mean excludes missing values, show how many recorded values it used.
5Answer questions with complete pipelines
A complete pipeline connects a question to a checkable answer. Decide which observations belong in the calculation, what each output row represents, and which measure answers the question. Then choose the verbs in that order. You will combine the running log into a pace report and check the intermediate tables, missing values, grouping, and totals that could otherwise hide a plausible-looking mistake.
5.1 Plan a pipeline from a question
Start a pipeline by describing the result in words. Decide what one row represents, which columns the answer needs, which input rows qualify, and how the result should be sorted. Those decisions determine the verbs and their order.
Plan an overall pace report
The question is "For each runner, what are the total distance and overall pace of runs with recorded distance, fastest first?" One output row represents one runner. The calculation needs run count, total kilometers, total minutes, and minutes per kilometer.
First choose the eligible runs. Then summarize within runner, compute the pace, and sort smaller pace values first:
runner_totals <- runs |>
filter(!is.na(distance_km)) |>
summarize(
n_runs = n(),
total_km = sum(distance_km),
total_min = sum(time_min),
.by = runner
) |>
mutate(pace_min_per_km = total_min / total_km) |>
arrange(pace_min_per_km)
Ben comes first: three runs, 24 km, and 140 minutes, or about 5.83 min/km. Chen has two included runs, 15.5 km, and 93 minutes, giving 6 min/km. Ana has four runs, 27.5 km, and 168 minutes, giving about 6.11 min/km.
Keep numerator and denominator on the same rows
Chen's omitted run has a known time of 41 minutes but an unknown distance. If you only added na.rm = TRUE to the distance sum, his time total would still be 134 minutes. Dividing that by 15.5 km gives about 8.65 min/km. The numerator would cover three runs and the denominator only two. Filtering the incomplete pair before both sums keeps their coverage aligned. In a table with missing times too, check both measurements when choosing eligible pairs.
Distinguish the quantity you want
An overall pace is total time divided by total distance. A mean of per-run paces gives equal weight to every run, regardless of distance. These are different measures. Ana's mean per-run pace is 6.1 min/km; her ratio of totals is about 6.11 min/km. Choose according to whether the question concerns the combined distance or the typical run.
Verb order also changes the population. filter(week >= 2) before a runner summary computes totals from later weeks only: Ana 22.5 km, Ben 16 km, Chen 9 km. A filter total_km > 20 after the all-week summary instead keeps whole runners, Ana and Ben, using their full recorded totals.
Move up one level at a time
runs |>
summarize(km = sum(distance_km, na.rm = TRUE),
.by = c(runner, week)) |>
summarize(best_week_km = max(km), .by = runner)
The first table has one row per runner-week. The second finds each runner's largest weekly total: 12.5 km for Ana, 12 for Ben, and 9 for Chen. Chen's all-missing week becomes zero with this sum rule; zero here is an empty recorded total, not a known distance. If that distinction matters to the report, also retain a recorded-value count.
Save reusable results under descriptive names, keep the raw table available, and include units in calculated column names. Those choices make the pipeline easier to rerun and its output easier to interpret.
Key Takeaways
- Describe output rows, columns, eligibility, and order before choosing verbs.
- Filter incomplete measurement pairs before computing a ratio of their totals.
- A ratio of totals and a mean of ratios answer different questions.
- Filtering before a summary selects observations; filtering after it selects summary groups.
- A second summary can move from runner-week results to runner results.
5.2 Check and debug a pipeline
A pipeline can run successfully and still answer the wrong question. Debugging includes checking table shape, grouping, missing values, and the meaning of the final numbers, as well as fixing errors.
Check the table after each verb
Build from a working first step. Run through the next verb without a trailing pipe, inspect the output, then continue. Compare it with the shape you predicted:
| Operation | Expected effect |
|---|---|
filter(), filter_out(), distinct() | Keep or remove rows. |
arrange() | Same rows in a different order. |
mutate() | Same row count, new or changed columns. |
select() | Same rows, chosen columns. |
summarize() | One row per group. |
slice_min(), slice_max() | Selected extremes, including ties by default. |
slice() can duplicate rows when positions repeat, and sampling with replacement can also repeat rows. So a larger output is not automatically a bug; compare it with the operation requested.
An empty filter result is a reason to inspect the condition and the actual values. "ana" does not match "Ana". Check spelling and capitalization before assuming the data contain no relevant observations.
Read the error where it starts
An error typically identifies the verb, the argument, and a cause. If filter() reports "object 'distnce_km' not found," inspect names(runs) or glimpse(runs) for the exact spelling. A column might also have been removed by an earlier select() or renamed before the failing step. Run the preceding stage to see which columns are actually present.
Messages have a different role. A tidyverse conflicts message reports which function names are masked. A summary grouping message reports the groups that remain in a completed result. The code ran, but a later calculation may use a scope you did not intend.
Check grouping and missingness directly
Use group_vars(result) or read the # Groups: line. An empty grouping list means the table is ungrouped. If an intended overall share comes out as 1 for each group, inspect grouping at the denominator step.
runs |> filter(is.na(distance_km))
runs |> summarize(missing = sum(is.na(distance_km)))
The first call displays the incomplete row; the second counts one missing distance. For an all-missing group, sum(x, na.rm = TRUE) returns 0 and mean(x, na.rm = TRUE) returns NaN. Neither provides an observed measurement. Retain a count of recorded values so an empty recorded total is recognizable.
Cross-check by a different route
The runner totals are 27.5, 24, and 15.5 km; their sum must equal the overall recorded 67 km when both calculations use the same rows. Compare count(runs, runner, wt = distance_km) with summarize(runs, total_km = sum(distance_km, na.rm = TRUE)). A mismatch sends you back to row selection, repeated rows, or differing missing-value rules.
Check routine syntax too: use <- to save a table, == for a filter comparison, and = to name a new column. Keep pipes at line ends and use + for plot layers. After a fix, rerun from the raw input so that old intermediate objects cannot conceal the effect of the change.
Key Takeaways
- Run and inspect one stage at a time.
- Use the expected row and column counts to locate a failing step.
- Read error causes and check the names present at that stage.
- Inspect persistent grouping before global calculations.
- All-missing sums can be zero while all-missing means are
NaN. - Compare grouped totals with an independent overall calculation.
Transforming Data with dplyr examples
1From a table to a readable pipeline
10 steps
- 1IntroductionKnow what enters each step
A transformation takes a table and returns a table with the changes you requested. We will use a running log in which one row is one run, then find and sort a subset of those runs, chaining the steps with the pipe and writing column names bare through data masking. Start by checking the structure: a runner can have several observations, and a missing distance is still a real row. The code should preserve that meaning while changing which observations you see.
- 2ExampleCreate the running log
Create the shared example after loading dplyr:
library(dplyr) runs <- tibble( runner = c("Ana", "Ben", "Chen", "Ana", "Ben", "Chen", "Ana", "Ben", "Chen", "Ana"), week = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 3), distance_km = c(5, 8, 6.5, 10, 12, NA, 7.5, 4, 9, 5), time_min = c(30, 44, 39, 62, 70, 41, 45, 26, 54, 31) )The units are kilometers and minutes. Chen's week-2 distance is unknown; Ana has two separate runs in week 3.
- 3ExplanationRead names and types
Run
glimpse(runs). You should see ten rows and four columns.runneris character text, marked<chr>; the other columns are double-precision numbers, marked<dbl>. A printed tibble gives the same types below the column names.The type tells you what calculations make sense. A numeric time can be divided by a distance. A runner's name identifies whose observation you are using.
- 4ExampleKeep the name bare
The call
filter(runs, runner == "Ben")asks dplyr to read the values in therunnercolumn and compare each with the text "Ben." It returns three rows and the original four columns.This direct access to column values is data masking. Writing
"runner" == "Ben"would compare two fixed words and give false. Quotes belong around the text value you want to match, while the column name stays bare. - 5ChallengeDid the original change?
You run
ben <- filter(runs, runner == "Ben"). How many rows are inben, and how many are still inruns?---reveal---
benhas three rows, andrunsstill has ten. The verb returned a new table and the assignment saved it under a new name. An assignment back torunswould replace that object, but savingbendoes not. This lets you inspect a subset while keeping the original observations available. - 6ExplanationRead the pipe as then
The pipe sends a result into the first argument of the next call. For example,
runs |> filter(week == 3)meansfilter(runs, week == 3).The four surviving rows are Ana 7.5 km, Ben 4 km, Chen 9 km, and Ana 5 km in their original order. A second verb receives this four-row result. It does not restart from all ten runs unless you explicitly write a different expression.
- 7ExampleAdd the sort and save the result
Join the operations in the order you need:
week3_longest <- runs |> filter(week == 3) |> arrange(desc(distance_km))The result is Chen 9 km, Ana 7.5 km, Ana 5 km, then Ben 4 km. Filtering chose the observations; sorting changed their order. The assignment saves the final table. Line-ending pipes signal that the command continues, and the indentation makes each new operation visible.
- 8TipRecognize a pipe syntax error
Use call parentheses after the native pipe:
runs |> nrow()is valid, while a barenrowis not. Older code may use%>%, which permits the bare form and has different placeholder rules.The native
|>is available in base R from 4.1.0. RStudio's Ctrl+Shift+M shortcut, or Cmd+Shift+M on a Mac, inserts the pipe chosen in its Code settings. Check which symbol your editor inserted before copying a mixed example. - 9ChallengeCheck one stage before plotting
You want to inspect the week-3 rows, then pass them into a scatterplot. What expression shows the intermediate table, and which operator will add
geom_point()afterggplot()?---reveal---
Run
runs |> filter(week == 3)to see the four-row stage without a trailing pipe. Pipe that data intoggplot()when ready, then use+ geom_point()to add the layer. Data passing and layer addition are different operations. - 10RecapA result you can follow
For the saved week-3 result, you can account for every stage: ten input rows, four rows after the condition, and the same four after the sort. Bare names identify columns, quoted values identify text to match, and the outer assignment names the final table.
Use this same habit on a longer chain: read the input, follow each verb, and inspect the first stage whose result differs from what the question needs.
2Choose the right rows
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionThree row questions
- 2ExampleCombine two requirements
- 3ExplanationExpress alternatives as membership
- 4Key InsightKeep unknowns when dropping matches
- 5ChallengeFind the incomplete observations
- 6ExampleSort two keys
- 7TipBring the unknown distance first
- 8ChallengeHas a sort reduced the data?
- 9ExampleChoose what unique means
- 10ExampleFind each runner's shortest run
- 11ConnectionPositions and random choices
- 12ChallengeLongest run or first run?
- 13RecapMatch the operation to the request
3Build columns you can trust
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFrom recorded values to useful measures
- 2ExampleCalculate pace for one row
- 3ExampleUse a newly created column
- 4TipPut inputs beside the answer
- 5ChallengeChoose the denominator's scope
- 6ExplanationLabel two outcomes and an unknown
- 7ExampleGive specific conditions first
- 8ExampleCalculate a change in week order
- 9Key InsightRunning totals retain unknown contributions
- 10ChallengePredict a tied rank
- 11ExampleSelect a readable view
- 12TipMake missing names an explicit choice
- 13ExampleRename and move without dropping
- 14ChallengeBuild a pace report
- 15RecapCheck inputs, scope, order, and names
4From runs to supported group summaries
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDecide what a summary row means
- 2ExampleSummarize recorded distances
- 3ExplanationUse a logical mean as a share
- 4ChallengeChoose one row or two
- 5ExampleMake one result per runner
- 6ExampleAdd week to the grouping
- 7Key InsightA surviving group changes the denominator
- 8TipUse one-operation groups when appropriate
- 9ChallengeMake the next calculation global
- 10ExampleCount rows and add counts
- 11ExplanationA weighted count is a total
- 12ChallengeCount runs or people?
- 13ExampleA highest mean with little support
- 14Key InsightUse the count behind the mean
- 15ChallengeChoose the eligible ranking
- 16ConnectionA count can also reveal a data problem
- 17RecapState the measure and its support
5Build and check a pace report
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTurn the question into a result table
- 2ExplanationChoose eligible measurements first
- 3ExampleSummarize the eligible runs
- 4ExampleCalculate and order the pace
- 5ChallengeFind the mismatched totals
- 6ConnectionMove up a summary level
- 7TipPredict and inspect the shapes
- 8ExampleRead a missing-column error
- 9Key InsightZero recorded total can hide no data
- 10ChallengeCross-check the completed analysis
- 11ChallengeDiagnose a perfect-looking share
- 12RecapRerun a report with a clear meaning
Transforming Data with dplyr practice questions
Set 1: Read tables and choose observations10 Practice Questions
Question 1 of 10
small <- filter(samples, mass_g > 20), what happens to the existing object samples?Show answerHide answer
<- saves that result under small. The original samples object is unchanged because nothing assigns a new value to that name. Treating the filtered display as a change to the original confuses a returned result with a saved replacement.Question 2 of 10
site contains "East", "West", and "East". Why does filter(readings, "site" == "East") return no rows?Show answerHide answer
"site" a fixed text value, so the condition compares it with the different text "East" and is false. Removing the quotes from site makes it refer to the column while keeping "East" as the target value. This is a naming error, not evidence that the table lacks East readings.Question 3 of 10
records |> select(id, score)?Show answerHide answer
records becomes the data argument of select(), followed by the chosen columns. Putting it after id would change which argument supplies the table.Question 4 of 10
logs |> filter(day == 4) |> arrange(delay_min). To inspect the filtered table before sorting, what expression should you run?Show answerHide answer
|> makes the expression incomplete, while running only the sort inspects a different stage that has not selected day 4.Question 5 of 10
batch = c(2, 4, 6, 2). How do you keep every row belonging to batch 2 or batch 6?Show answerHide answer
%in% tests every batch against both permitted values, keeping the first, third, and fourth rows. batch == c(2, 6) instead recycles 2 and 6 across positions and misses qualifying rows. Comma-separated equalities would require a single row to have both batch values.Question 6 of 10
mass_g = c(14, NA, 18), how many rows remain after filter_out(x, mass_g == 14) in dplyr 1.2?Show answerHide answer
filter(mass_g != 14) would incorrectly remove the unknown row too; filter_out() retains it.Question 7 of 10
c(9, NA, 3, 7) in score. What is their order after arrange(x, desc(score))?Show answerHide answer
desc() puts the recorded scores in decreasing order, and missing values remain last for a local data frame. Sorting does not remove the missing row. Moving NA to the front would require an explicit missingness sort key; reversing a numeric sort alone does not do that.Question 8 of 10
person = c("Ivo", "Mira", "Ivo") and score = c(6, 8, 9). What scores survive distinct(x, person, .keep_all = TRUE)?Show answerHide answer
distinct() keeps the first occurrence of each person, and .keep_all = TRUE retains its score. Ivo first appears with 6, so his later 9 is not chosen. Selecting the highest score per person would require an extreme-value operation or a preceding sort that puts that score first.Question 9 of 10
(id, zone, value) of (1, "A", NA), (2, "A", 11), (3, "B", 16), and (4, "C", 19). The code is filter(x, zone == "A" | zone == "B" & value > 14). The intended result is only recorded values above 14 from A or B. Which IDs appear incorrectly, and what condition fixes it?Show answerHide answer
& binds before |, so every A row passes even when its value is low or missing; only B rows face the value test. IDs 1 and 2 therefore appear incorrectly, while ID 3 is the intended result. Parenthesizing the B branch alone leaves that faulty A shortcut unchanged; apply the value test to the combined zone selection.Question 10 of 10
(id, team, points) of (1, "X", 8), (2, "X", 8), (3, "Y", 6), (4, "Y", NA), (5, "Y", 4). What IDs remain after x |> slice_max(points, n = 1, by = team) |> arrange(id) |> slice_tail(n = 2)?Show answerHide answer
slice_max() retains them by default.Set 2: Calculate and organize useful columns10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
mutate(x, pace_min_per_km = time_min / distance_km) put in its pace column?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
id, mass_g, and time_s. What does mutate(x, rate_g_per_s = mass_g / time_s, .keep = "used") return?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
score = c(7, 10, NA), what labels result from case_when(score >= 7 ~ "pass", score >= 10 ~ "high", .default = "review")?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
if_else(temp_c > 25, "warm", "cool") explicitly label an unknown condition "unknown"?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
visits has columns id, duration_min, and site. What call changes duration_min to minutes while retaining all three columns?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
id, q1_text, q1_score, and q2_score, what does select(x, starts_with("q1") & !ends_with("_text")) keep?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
(person, day, value) of ("Nia", 2, 14), ("Omar", 1, 9), ("Nia", 1, 8), and ("Omar", 2, 7). After arrange(person, day) |> mutate(delta = value - lag(value), .by = person), what are the day-2 changes for Nia and Omar?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
c(12, 12, 8, NA, 5). A pipeline adds r = min_rank(desc(value)), keeps r <= 2, and then adds total = cumsum(value). How many rows remain, and what is the final running total?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
id, mass_g, and time_s. Let cols <- c("id", "mass_g", "rate"). What names and order result from x |> select(any_of(cols)) |> rename(mass = mass_g) |> relocate(mass)?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
x$name are "pear", "Zucchini", and "banana". Under default C-locale ordering, what full order does arrange(x, name) produce?Show answerHide answer
Save this lesson to see this answer.
Set 3: Summarize groups and judge the evidence10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
c(3, NA, 9). What does summarize(x, total = sum(value, na.rm = TRUE)) return for total?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
height_cm = c(150, 170, NA, 180, NA). What does mean(height_cm >= 170, na.rm = TRUE) report inside summarize()?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
group_by(region, site) |> summarize(total = sum(value)), which grouping remains by default?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
(region, site, value) are ("A", "p", 2), ("A", "q", 6), ("B", "r", 12). What share does site q get from group_by(region, site) |> summarize(v = sum(value)) |> mutate(share = v / sum(v)), and what change makes it a share of all recorded value?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
person = c("Luz", "Luz", "Kai", "Kai"). What does n_distinct(person) return in a summary?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
hub = c("E", "E", "W") and mass_kg = c(4, NA, 7). What does count(x, hub, wt = mass_kg, name = "total_kg") give?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
zone = c("N", "N", "S", "S", "S") and person = c("A", "B", "C", "C", "D"). After add_count(zone) |> filter(n >= 3) |> summarize(rows = n(), people = n_distinct(person)), what result appears?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
yield_g values, and a recorded mean of 92 g. Site Q has six rows, one missing value, and a mean of 85 g. Site R has five rows, no missing values, and a mean of 88 g. A report requires at least four measurements used in a mean and ranks eligible sites by mean descending. What is the final ranking?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
(team, shift) of ("Z", 2), ("A", 1), ("Z", 2), ("Z", 1). What are the result row count and grouping after summarize(x, rows = n(), .by = c(team, shift)), and which combination comes first?Show answerHide answer
Save this lesson to see this answer.
Set 4: Plan and debug complete analyses10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
(distance_km, time_min) of (4, 12) and (12, 48). A third has (NA, 20). For trips with known distance, what are the overall minutes per kilometer and the mean of per-trip minutes per kilometer?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
value entries. What pair results from sum(value, na.rm = TRUE) and mean(value, na.rm = TRUE)?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
(site, week, mass_kg) are ("P", 1, 4), ("P", 1, 7), ("P", 2, 9), ("Q", 1, 8), ("Q", 2, 6). A report needs each site's largest weekly total. What totals should it return?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
event_id, site, and mass_g. Its rows are (1, "A", 6), (2, "A", 6), (3, "A", 4), (4, "B", 5), and (5, "B", 9). All five are real observations. What total does x |> select(site, mass_g) |> distinct() |> summarize(total = sum(mass_g)) return, and how can the pipeline retain all observations?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
x is saved after group_by(region). Its rows (region, site, value) are ("A", "p", 2), ("A", "q", 4), and ("B", "r", 6). The pipeline x |> summarize(v = sum(value), .by = c(region, site)) |> mutate(share = v / sum(v)) fails. How should it change, and what share should site q receive?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
(team, value) of ("A", 5), ("B", 10), ("A", NA), ("B", 3), ("A", 4). After mutate(x, total = cumsum(value), .by = team) |> filter(!is.na(total)), which values remain in total, in output order?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
slice(x, c(2, 2, 5)) return?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
C
Column type
glimpse(runs) marks runner names as <chr> and distances as <dbl>.Count proportion
n / sum(n) gives weekly shares of 0.3, 0.3, and 0.4.Cumulative sum
cumsum() turns one runner's distances into running totals of 5, 15, 22.5, and 27.5 km in row order.D
Data masking
filter() and mutate().filter(runs, runner == "Ben"), runner reads the column while "Ben" is a text value.Dense rank
dense_rank(desc(distance_km)), a 4 km run after them gets rank 8.Descending order
arrange(), desc() reverses the ordering of the column it wraps.arrange(runs, desc(distance_km)) starts with the longest run and leaves any missing distance last.Distinct count
n_distinct() instead of counting every observation.dplyr
library(dplyr) before using its verbs to explore a log of runs stored as a data frame.E
Error message
F
First-appearance order
.by preserves in summary output..by summary even when an "A" key appears later.G
Group size
Group-relative value
.by = runner.Grouping key
I
Informational message
L
Lag
lag(x) supplies the previous value within each calculation group.Lead
lead(x) supplies the next value and is missing at the end by default.Locale
.locale = "en" requests English dictionary ordering.Logical condition
distance_km >= 7 gives true for recorded runs of 7 km or more and an unknown result for a missing distance.Logical mean
Logical sum
sum(distance_km >= 8, na.rm = TRUE) counts the recorded runs reaching 8 km.M
magrittr pipe
%>%, is an earlier pipe available with dplyr that uses . as a placeholder and permits a bare function name.runs %>% nrow, while the native form needs runs |> nrow().Mean of ratios
Membership test
%in% to ask whether each value belongs to a supplied set, comparing it with the whole set independently of row position.week %in% c(1, 3) selects runs from either week without recycling comparisons.Minimum group size
Minimum rank
min_rank() are followed by rank 9, not rank 8.Missing value
NA in R, represents an unknown entry whose ordinary comparisons and arithmetic usually remain unknown.N
Namespace
package::function() to resolve functions with the same name.dplyr::filter() makes the row-filtering choice explicit when another package also defines filter().NaN
NaN with removal, even though its corresponding empty sum is 0.Native pipe
|>, passes a value into the first argument of the following ordinary function call, allowing steps to read in sequence.runs |> filter(week == 3) feeds the runs table into the filter before any later operation.O
Output level
P
Pace
Pipeline
Placeholder
_ can appear once as a named argument or head an extraction chain.runs |> lm(time_min ~ distance_km, data = _) sends runs to the named data argument.R
Random seed
set.seed(42) immediately before the sample when you want the same random selection again.Ratio of totals
Recorded-value count
sum(!is.na(distance_km)) reports the number of distances used when a mean removes missing values.Reproducible analysis
S
Sampling without replacement
slice_sample(runs, n = 3) chooses three rows without repetition unless replace = TRUE is supplied.Selection helper
ends_with("_score") selects every column whose name ends in _score without reading its values.Slice
slice(runs, 2:4) keeps positions 2 through 4 in the current order of the table.Small-group variability
Sort key
arrange(runs, runner, desc(time_min)), time breaks ties among rows with the same runner name.Summary statistic
T
Table shape
Tibble
Tidy selection
.by = c(runner, week) uses tidy selection to choose grouping columns for one verb.Tie
V
Vectorized calculation
time_min / distance_km, each run's time is paired with that same row's distance throughout a log of runs.Verb
filter(runs, week == 2) uses a row verb to keep only the observations from week 2.W
Weighted count
wt = distance_km and name = "total_km" to report recorded distance totals by runner.Window function
#
`.by`
.by argument selects grouping columns for a single operation on ungrouped data, without attaching groups to the output.summarize(runs, n = n(), .by = runner) counts each runner and returns ungrouped results.`.groups`
.groups argument controls grouping left after summarize(), including dropping the last level, dropping all levels, or keeping them..groups = "drop" lets a following share calculation see all summary rows.`.keep_all`
.keep_all argument makes distinct() retain the other columns from the first row associated with each selected unique combination.distinct(runs, runner, .keep_all = TRUE) retains each runner's first recorded run with its time and distance.`.keep`
.keep argument controls which existing columns remain after mutate(), while new and grouping columns remain available.mutate() computes pace from distance and time, .keep = "used" shows those inputs beside the pace for a compact checking view.`add_count()`
add_count() function appends a group count to each original observation, retaining all input rows for later row-level work.add_count(runner), each of a runner's four runs has its runner count recorded as 4.`all_of()`
all_of() helper selects columns named in a character vector and stops with an error if any requested name is absent.all_of(cols) when a report cannot be calculated correctly without every column listed in cols.`any_of()`
any_of() helper selects the existing columns named in a character vector, skipping requested names that are absent from the table.any_of(c("runner", "pace")) keeps runner because pace has not been created.`arrange()`
arrange() function sorts whole rows by one or more column expressions, preserving the table's observations and their values.arrange(runs, runner, week) displays runner names first, with weeks ordered within each name.`between()`
between() function tests whether a value lies within a range including both endpoints, returning a logical result for each value.between(distance_km, 5, 8) includes 5 km and 8 km runs as well as recorded distances between them.`case_when()`
case_when() function assigns each row the outcome of its first true condition, using an optional default when no condition matches.`count()`
count() function returns counts by category or combination, temporarily grouping the data and preserving the input's persistent groups.count(runs, runner) returns three rows with those counts.`distinct()`
distinct() function keeps unique whole rows or unique combinations of selected columns, retaining the first occurrence of each match.distinct(runs, runner, week) keeps a runner who appears twice in the same week as a single runner-week combination.`filter_out()`
filter_out() function drops rows whose combined condition is true and retains false or missing results; it requires dplyr 1.2 or later.filter_out(runs, distance_km == 5) removes the known 5 km runs but keeps rows whose distance is unknown.`filter()`
filter() function keeps rows whose combined condition is true, dropping false and missing results while preserving the retained row order.filter(runs, week == 2) returns every week-2 row with all of its original columns.`group_by()`
group_by() function attaches persistent grouping structure to a table so later calculations operate within the specified groups.group_by(runner) also saves its grouping state for later verbs.`group_vars()`
group_vars() function lists a table's persistent grouping columns, returning an empty character vector when there are no groups.group_vars(result) before computing a denominator intended to cover the entire result.`if_else()`
if_else() function selects between compatible true and false outcomes for each row, with a separate optional outcome for a missing condition.missing = "unknown" labels in a new column.`mutate()`
mutate() function creates or replaces columns using expressions evaluated on a table, while preserving its number of observations.mutate(runs, pace = time_min / distance_km) adds a pace value beside every original run.`n()`
n() function returns the current group's number of rows inside a dplyr verb, including rows with missing measurements.summarize(runs, n_runs = n()) counts every row, including rows whose distance is unknown.`na.rm`
na.rm argument asks a supporting calculation to remove missing inputs before computing its result, without recovering their unknown values.sum(distance_km, na.rm = TRUE) totals only the recorded distances but does not estimate a missing one.`near()`
near() function compares numbers using a small tolerance, so tiny differences caused by decimal storage need not fail an equality check.near(0.1 + 0.2, 0.3) is true even though exact equality for that calculation is false in R.`reframe()`
reframe() function creates a result table from expressions that may return several rows per group, allowing outputs beyond one-row summaries.reframe(runs, km = range(distance_km, na.rm = TRUE)) returns the two recorded extremes.`relocate()`
relocate() function moves selected columns to the front or a specified before/after position without dropping columns or changing rows.relocate(runs, time_min, .before = week) places time immediately before week in the displayed table.`rename()`
rename() function changes column names using new_name = old_name, retaining other columns and their existing order.rename(runs, km = distance_km) changes the distance label without dropping time or week.`select()`
select() function retains and orders specified columns, choosing names directly or through helpers while preserving the input rows.select(runs, runner, distance_km) gives a two-column view that keeps every run.`summarize()`
summarize() function reduces each group to one row of named summary values, returning one overall row when the input has no groups.`tally()`
tally() function counts rows, or adds supplied weights, using the groups already attached to its input table.runs |> group_by(week) |> tally() reports a run count for each week without naming week again.`ungroup()`
ungroup() function removes persistent grouping from a table, allowing later calculations to use the whole table as one scope.ungroup() before calculating a share whose denominator should include every runner.- 1R and RStudio
- 2Data Visualization with ggplot2
- 3Transforming Data with dplyr
- 4Tidy Data and Data Import in R
- 5Strings and Factors in R
- 6Joins in R
- 7Exploratory Analysis in R
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.