Transforming Data with dplyr

Learn to turn a raw data frame into the table that answers your question. Keep, drop and sort rows with 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

  1. 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 work
      Load 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 pipe
      Write multi-step transformations as pipelines with |>, read them as a sequence of steps, lay them out clearly, and know how |> differs from %>%.
  2. 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 value
      Remove duplicate rows with distinct(), and keep the first, last, largest, smallest or random rows with the slice functions, overall or per group.
  3. 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 values
      Assign 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 columns
      Pick columns by name, range, pattern or type with select(), rename them with rename() and rename_with(), and move them with relocate().
  4. 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 .by
      Split 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 values
      Count 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 size
      Report counts next to averages, recognize misleading results from small groups, and set a minimum group size before ranking.
  5. 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 question
      Translate 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 pipeline
      Run pipelines step by step, compare each result with the shape you expect, read errors and messages, and cross-check totals and missing values.

Transforming Data with dplyr study guide

5 chapters

1

Work 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.

FormHow 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 tablesFollow the names from one command to the next.
A pipelineRead 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:

FeatureNative pipemagrittr pipe
Function callruns |> 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) passes x as the first argument of f().
  • 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.
2

Choose 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:

CallResult
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 = TRUE retains 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() or slice_max() return more rows than requested.
  • Slice helpers use by; slice() uses .by.
  • Set a seed before a reproducible random sample.
3

Create 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:

ValueExisting 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 .keep to 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:

HelperExample 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() uses new = old and 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().
4

Summarize 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
PurposeFunctions
Total or centersum(), mean(), median()
Spreadsd(), IQR()
Smallest or largestmin(), max()
Value at a positionfirst(), last(), nth()
Rows or different valuesn(), 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 = TRUE excludes 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 valueResult
"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" or ungroup() before whole-table calculations.
  • .by groups one operation and preserves first-appearance group order.
  • Use .by on 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.
  • wt turns 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.
5

Answer 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:

OperationExpected 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

5 Walkthroughs

1

From a table to a readable pipeline

10 steps
Inspect a running log, choose a verb, and follow a saved pipeline one step at a time.
  1. 1
    IntroductionKnow 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.

  2. 2
    ExampleCreate 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.

  3. 3
    ExplanationRead names and types

    Run glimpse(runs). You should see ten rows and four columns. runner is 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.

  4. 4
    ExampleKeep the name bare

    The call filter(runs, runner == "Ben") asks dplyr to read the values in the runner column 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.

  5. 5
    ChallengeDid the original change?

    You run ben <- filter(runs, runner == "Ben"). How many rows are in ben, and how many are still in runs?

    ---reveal---

    ben has three rows, and runs still has ten. The verb returned a new table and the assignment saved it under a new name. An assignment back to runs would replace that object, but saving ben does not. This lets you inspect a subset while keeping the original observations available.

  6. 6
    ExplanationRead the pipe as then

    The pipe sends a result into the first argument of the next call. For example, runs |> filter(week == 3) means filter(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.

  7. 7
    ExampleAdd 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.

  8. 8
    TipRecognize a pipe syntax error

    Use call parentheses after the native pipe: runs |> nrow() is valid, while a bare nrow is 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.

  9. 9
    ChallengeCheck 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() after ggplot()?

    ---reveal---

    Run runs |> filter(week == 3) to see the four-row stage without a trailing pipe. Pipe that data into ggplot() when ready, then use + geom_point() to add the layer. Data passing and layer addition are different operations.

  10. 10
    RecapA 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.

2

Choose the right rows

13 steps
Filter incomplete observations deliberately, sort rows, and choose unique or extreme records.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionThree row questions
  2. 2
    ExampleCombine two requirements
  3. 3
    ExplanationExpress alternatives as membership
  4. 4
    Key InsightKeep unknowns when dropping matches
  5. 5
    ChallengeFind the incomplete observations
  6. 6
    ExampleSort two keys
  7. 7
    TipBring the unknown distance first
  8. 8
    ChallengeHas a sort reduced the data?
  9. 9
    ExampleChoose what unique means
  10. 10
    ExampleFind each runner's shortest run
  11. 11
    ConnectionPositions and random choices
  12. 12
    ChallengeLongest run or first run?
  13. 13
    RecapMatch the operation to the request
3

Build columns you can trust

15 steps
Calculate pace, add conditional and ordered values, and present the result with clear column names.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFrom recorded values to useful measures
  2. 2
    ExampleCalculate pace for one row
  3. 3
    ExampleUse a newly created column
  4. 4
    TipPut inputs beside the answer
  5. 5
    ChallengeChoose the denominator's scope
  6. 6
    ExplanationLabel two outcomes and an unknown
  7. 7
    ExampleGive specific conditions first
  8. 8
    ExampleCalculate a change in week order
  9. 9
    Key InsightRunning totals retain unknown contributions
  10. 10
    ChallengePredict a tied rank
  11. 11
    ExampleSelect a readable view
  12. 12
    TipMake missing names an explicit choice
  13. 13
    ExampleRename and move without dropping
  14. 14
    ChallengeBuild a pace report
  15. 15
    RecapCheck inputs, scope, order, and names
4

From runs to supported group summaries

17 steps
Compute summaries and counts, control grouping, and assess the size behind a reported mean.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDecide what a summary row means
  2. 2
    ExampleSummarize recorded distances
  3. 3
    ExplanationUse a logical mean as a share
  4. 4
    ChallengeChoose one row or two
  5. 5
    ExampleMake one result per runner
  6. 6
    ExampleAdd week to the grouping
  7. 7
    Key InsightA surviving group changes the denominator
  8. 8
    TipUse one-operation groups when appropriate
  9. 9
    ChallengeMake the next calculation global
  10. 10
    ExampleCount rows and add counts
  11. 11
    ExplanationA weighted count is a total
  12. 12
    ChallengeCount runs or people?
  13. 13
    ExampleA highest mean with little support
  14. 14
    Key InsightUse the count behind the mean
  15. 15
    ChallengeChoose the eligible ranking
  16. 16
    ConnectionA count can also reveal a data problem
  17. 17
    RecapState the measure and its support
5

Build and check a pace report

12 steps
Plan an end-to-end pipeline, align its measurements, and verify the result independently.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTurn the question into a result table
  2. 2
    ExplanationChoose eligible measurements first
  3. 3
    ExampleSummarize the eligible runs
  4. 4
    ExampleCalculate and order the pace
  5. 5
    ChallengeFind the mismatched totals
  6. 6
    ConnectionMove up a summary level
  7. 7
    TipPredict and inspect the shapes
  8. 8
    ExampleRead a missing-column error
  9. 9
    Key InsightZero recorded total can hide no data
  10. 10
    ChallengeCross-check the completed analysis
  11. 11
    ChallengeDiagnose a perfect-looking share
  12. 12
    RecapRerun a report with a clear meaning

Transforming Data with dplyr practice questions

40 Practice Questions in 4 sets

Set 1: Read tables and choose observations10 Practice Questions

Question 1 of 10

After small <- filter(samples, mass_g > 20), what happens to the existing object samples?
  1. It contains only rows above 20 g.
  2. It gains a logical condition column.
  3. It retains its previous rows.
  4. It is replaced by the object small.
Show answerHide answer
Answer: C
The verb returns a new table, and <- 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

A column site contains "East", "West", and "East". Why does filter(readings, "site" == "East") return no rows?
  1. It compares the site column case-insensitively.
  2. It compares two fixed text values.
  3. It looks for a column named East.
  4. It treats every site value as missing.
Show answerHide answer
Answer: B
Quotes make "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

What ordinary function call is equivalent to records |> select(id, score)?
  1. select(records, id, score)
  2. select(id, score, records)
  3. records(select(id, score))
  4. select(id, records, score)
Show answerHide answer
Answer: A
The native pipe places its left-hand value into the first argument of the call on its right. Here 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

A script contains logs |> filter(day == 4) |> arrange(delay_min). To inspect the filtered table before sorting, what expression should you run?
  1. logs |> filter(day == 4) |>
  2. logs |> arrange(delay_min)
  3. filter(day == 4) |> logs
  4. logs |> filter(day == 4)
Show answerHide answer
Answer: D
Run the pipeline through the filter and stop before the next pipe. That produces the intermediate table you want to inspect. Leaving a trailing |> makes the expression incomplete, while running only the sort inspects a different stage that has not selected day 4.

Question 5 of 10

A table has batch = c(2, 4, 6, 2). How do you keep every row belonging to batch 2 or batch 6?
  1. filter(x, batch == c(2, 6))
  2. filter(x, batch %in% c(2, 6))
  3. filter(x, batch == 2 | 6)
  4. filter(x, batch == 2, batch == 6)
Show answerHide answer
Answer: B
%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

With mass_g = c(14, NA, 18), how many rows remain after filter_out(x, mass_g == 14) in dplyr 1.2?
  1. One row.
  2. Three rows.
  3. Two rows.
  4. No rows.
Show answerHide answer
Answer: C
The 14 g row makes the condition true and is dropped. The 18 g row is false and the missing row is unknown, so both remain. Applying the behavior of filter(mass_g != 14) would incorrectly remove the unknown row too; filter_out() retains it.

Question 7 of 10

A table has values c(9, NA, 3, 7) in score. What is their order after arrange(x, desc(score))?
  1. 9, 7, 3, NA.
  2. NA, 9, 7, 3.
  3. 3, 7, 9, NA.
  4. 9, 7, 3 only.
Show answerHide answer
Answer: A
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

In current row order, person = c("Ivo", "Mira", "Ivo") and score = c(6, 8, 9). What scores survive distinct(x, person, .keep_all = TRUE)?
  1. 9 for Ivo and 8 for Mira.
  2. 6 and 9 for Ivo; 8 for Mira.
  3. 6 for Ivo, with score removed.
  4. 6 for Ivo and 8 for Mira.
Show answerHide answer
Answer: D
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

Four sensor rows have (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?
  1. ID 1 only; zone == "A" | (zone == "B" & value > 14).
  2. IDs 1 and 2; (zone %in% c("A", "B")) & value > 14.
  3. ID 2 only; (zone %in% c("A", "B")) | value > 14.
  4. IDs 1 and 4; zone == "A" & zone == "B" & value > 14.
Show answerHide answer
Answer: B
& 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

A table in this order contains (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)?
  1. IDs 2 and 3.
  2. IDs 1 and 3.
  3. IDs 3 and 4.
  4. IDs 1 and 2.
Show answerHide answer
Answer: A
The group maxima keep both tied X rows, IDs 1 and 2, and Y's recorded maximum, ID 3. After sorting by ID, the last two rows are 2 and 3. Keeping only ID 1 from X assumes ties were disabled, but 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

A journey takes 24 minutes and covers 6 km. What does mutate(x, pace_min_per_km = time_min / distance_km) put in its pace column?
  1. 0.25 min/km.
  2. 144 min/km.
  3. 30 min/km.
  4. 4 min/km.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An ungrouped table has four rows and columns id, mass_g, and time_s. What does mutate(x, rate_g_per_s = mass_g / time_s, .keep = "used") return?
  1. Four rows: id and rate_g_per_s.
  2. Four rows: mass_g, time_s, and rate_g_per_s.
  3. One row: mass_g, time_s, and rate_g_per_s.
  4. Four rows: id, mass_g, time_s, and rate_g_per_s.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

For score = c(7, 10, NA), what labels result from case_when(score >= 7 ~ "pass", score >= 10 ~ "high", .default = "review")?
  1. "pass", "pass", "review".
  2. "pass", "high", "review".
  3. "pass", "pass", NA.
  4. "pass", "high", NA.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

How can if_else(temp_c > 25, "warm", "cool") explicitly label an unknown condition "unknown"?
  1. Add .default = "unknown".
  2. Add na.rm = TRUE.
  3. Add missing = "unknown".
  4. Add .keep = "unknown".
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

The table visits has columns id, duration_min, and site. What call changes duration_min to minutes while retaining all three columns?
  1. rename(visits, duration_min = minutes)
  2. rename(visits, minutes = duration_min)
  3. select(visits, minutes = duration_min)
  4. relocate(visits, minutes, .after = id)
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

With columns id, q1_text, q1_score, and q2_score, what does select(x, starts_with("q1") & !ends_with("_text")) keep?
  1. q1_score only.
  2. q1_text and q1_score.
  3. q1_score and q2_score.
  4. id and q1_score.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Rows are (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?
  1. Nia -6; Omar 2.
  2. Nia 5; Omar -7.
  3. Nia 6; Omar 7.
  4. Nia 6; Omar -2.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Values in order are 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?
  1. Three rows; final total 32.
  2. Two rows; final total 12.
  3. Two rows; final total 24.
  4. Four rows; final total NA.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An ungrouped table has 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)?
  1. id, mass, rate.
  2. id, mass, time_s.
  3. mass, id.
  4. mass_g, id.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Names in x$name are "pear", "Zucchini", and "banana". Under default C-locale ordering, what full order does arrange(x, name) produce?
  1. "Zucchini", "banana", "pear".
  2. "banana", "pear", "Zucchini".
  3. "pear", "banana", "Zucchini".
  4. "Zucchini", "pear", "banana".
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

A measurement column contains c(3, NA, 9). What does summarize(x, total = sum(value, na.rm = TRUE)) return for total?
  1. NA.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Five rows have height_cm = c(150, 170, NA, 180, NA). What does mean(height_cm >= 170, na.rm = TRUE) report inside summarize()?
  1. The share 2/5 of all rows.
  2. The share 3/5 of all rows.
  3. The share 2/3 of recorded heights.
  4. The share 1/3 of recorded heights.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

After group_by(region, site) |> summarize(total = sum(value)), which grouping remains by default?
  1. Grouping by site.
  2. Grouping by both columns.
  3. No grouping columns.
  4. Grouping by region.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Rows (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?
  1. 0.30; add .groups = "keep" to the summary.
  2. 0.75; add .groups = "drop" to the summary.
  3. 0.75; add na.rm = TRUE to the denominator.
  4. 0.30; add arrange(desc(v)) before the share.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A table has four rows with 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

Three parcel rows have hub = c("E", "E", "W") and mass_kg = c(4, NA, 7). What does count(x, hub, wt = mass_kg, name = "total_kg") give?
  1. E: 2 kg; W: 1 kg.
  2. E: NA; W: 7 kg.
  3. E: 4 kg; W: 11 kg.
  4. E: 4 kg; W: 7 kg.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Records have 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?
  1. 3 rows and 2 people.
  2. 2 rows and 2 people.
  3. 5 rows and 4 people.
  4. 1 row and 3 people.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A rating summary has means and recorded counts: Alder 4.9 from 3, Birch 4.7 from 42, Cedar 4.6 from 65. A report includes groups with at least 15 recorded ratings and ranks mean descending. Which group leads the report?
  1. Alder.
  2. Cedar.
  3. Birch.
  4. Alder and Birch tie.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Site P has eight rows, six missing 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?
  1. P, then R, then Q; use total row counts.
  2. R, then Q; use non-missing measurement counts.
  3. Q, then R; use non-missing measurement counts.
  4. R only; exclude every site with missing values.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Rows appear with keys (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?
  1. Four ungrouped rows; Z, shift 2 first.
  2. Three rows grouped by team; A, shift 1 first.
  3. Three ungrouped rows; A, shift 1 first.
  4. Three ungrouped rows; Z, shift 2 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

A call fails with "object 'lenght_cm' not found". What should you inspect first in the table entering that call?
  1. Its stored text values.
  2. Its exact column names.
  3. Its result object names.
  4. Its grouping columns.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

You need average mass per site for observations from month 6 only, largest average first. What order of operations matches that request?
  1. Summarize by site, filter month, sort the mean descending.
  2. Filter month, sort mass descending, select the first site.
  3. Filter month, summarize by site, sort the mean descending.
  4. Summarize by month, filter site, sort the mean ascending.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Two trips by one cyclist have (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?
  1. Overall 3.75; per-trip mean 3.5.
  2. Overall 5; per-trip mean 3.5.
  3. Overall 3.5; per-trip mean 3.75.
  4. Overall 3.75; per-trip mean 2.33.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A group contains only missing value entries. What pair results from sum(value, na.rm = TRUE) and mean(value, na.rm = TRUE)?
  1. NA and NA.
  2. 0 and 0.
  3. NaN and 0.
  4. 0 and NaN.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Rows (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?
  1. P: 9 kg; Q: 8 kg.
  2. P: 20 kg; Q: 14 kg.
  3. P: 11 kg; Q: 8 kg.
  4. P: 11 kg; Q: 14 kg.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

An ungrouped table has columns 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?
  1. 24 g; keep event_id in the selection before distinct().
  2. 24 g; add .keep_all = TRUE to distinct().
  3. 30 g; keep event_id in the selection before distinct().
  4. 30 g; add .keep_all = TRUE to distinct().
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A table 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?
  1. Ungroup before the summary; q gets 2/3.
  2. Keep the groups and set .groups = "drop"; q gets 1/3.
  3. Remove .by from the summary; q gets 1/3.
  4. Ungroup before the summary; q gets 1/3.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Rows in time order have (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?
  1. 5, 15, 18.
  2. 5, 10, 13.
  3. 5, 10, 13, 9.
  4. 5, 10 only.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A table contains five rows. What does slice(x, c(2, 2, 5)) return?
  1. Two rows, original rows 2 and 5 once.
  2. Five rows, sorted by positions 2 and 5.
  3. Three rows, with original row 2 twice.
  4. An error because positions repeat.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Two sites have recorded reading totals and counts: R has total 40 from 2 readings, S has total 90 from 6. A report claims the pooled mean is the mean of the two site means. What is the pooled mean, and why does that claim fail?
  1. 16.25; the two site means have unequal support.
  2. 17.5; each site contributes one summary row.
  3. 16.25; pooled means ignore group totals.
  4. 17.5; the larger site must receive less weight.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

79 Key Terms, each with its definition

C

Column type
A column type identifies the kind of values a column stores, such as character, double, integer, or logical, and guides valid calculations.
glimpse(runs) marks runner names as <chr> and distances as <dbl>.
Count proportion
A count proportion divides one category's count by the relevant total count, with the denominator determined by the calculation's groups.
For ten runs counted by week without groups, n / sum(n) gives weekly shares of 0.3, 0.3, and 0.4.
Cumulative sum
A cumulative sum adds values from the beginning of a sequence through the current row; an unknown contribution makes later totals unknown.
cumsum() turns one runner's distances into running totals of 5, 15, 22.5, and 27.5 km in row order.

D

Data masking
Data masking lets an expression refer directly to column values by their bare names inside verbs such as filter() and mutate().
In filter(runs, runner == "Ben"), runner reads the column while "Ben" is a text value.
Dense rank
A dense rank gives equal values the same rank and continues with the next consecutive rank, leaving no gaps after tied values.
If two 5 km runs share rank 7 under dense_rank(desc(distance_km)), a 4 km run after them gets rank 8.
Descending order
Descending order places larger values before smaller ones; in 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
A distinct count measures how many different values occur in a column, using n_distinct() instead of counting every observation.
A week with four run rows from three runners has a distinct runner count of three.
dplyr
dplyr is a tidyverse package that transforms data frames with functions for choosing rows, computing columns, and summarizing groups.
Load library(dplyr) before using its verbs to explore a log of runs stored as a data frame.

E

Error message
An error message reports a failure that prevents a call from completing, often naming the verb, argument, and underlying cause.
An unknown-column error prompts a check of spelling and of columns present after earlier selections.

F

First-appearance order
First-appearance order lists group combinations in the sequence they first occur in the input, which .by preserves in summary output.
A key first seen as "Z" can stay first in a .by summary even when an "A" key appears later.

G

Group size
Group size is the number of observations in a group; the count supporting a measurement summary may be smaller when values are missing.
A runner's group can have three run rows while only two recorded distances support that runner's distance mean.
Group-relative value
A group-relative value compares an observation with a calculation from its own group, such as its share of that group's total.
A runner's 12 km run is half of a 24 km total when the share is computed with .by = runner.
Grouping key
A grouping key is a column whose shared values define rows to be calculated together; multiple keys define combinations of values.
Runner and week together put two runs by the same runner in the same week into one group because they share both keys.

I

Informational message
An informational message reports something about completed work, such as remaining grouping or masked function names, without being an error.
A grouped-summary message explains why a following share may still be calculated separately by runner.

L

Lag
A lag is an earlier row's value in the current sequence; lag(x) supplies the previous value within each calculation group.
After sorting by week, a runner's change from 12 km to 4 km is found by subtracting the previous distance.
Lead
A lead is a later row's value in the current sequence; lead(x) supplies the next value and is missing at the end by default.
A next-run distance column must use the intended time order and stay within each runner's group.
Locale
A locale supplies language-related ordering rules for text; current dplyr defaults to C ordering unless a different locale is requested.
The C locale puts "Banana" before "apple"; .locale = "en" requests English dictionary ordering.
Logical condition
A logical condition is an expression evaluated as true, false, or missing for each row, allowing a verb to decide which rows qualify.
distance_km >= 7 gives true for recorded runs of 7 km or more and an unknown result for a missing distance.
Logical mean
A logical mean gives the proportion of true results among the logical values included in the calculation, using true as 1 and false as 0.
When four of nine recorded runs are long, the long-run share is four out of nine once an unknown distance comparison is removed.
Logical sum
A logical sum counts true results by adding logical values as 1 for true and 0 for false, with missing results handled explicitly.
sum(distance_km >= 8, na.rm = TRUE) counts the recorded runs reaching 8 km.

M

magrittr pipe
The magrittr pipe, %>%, is an earlier pipe available with dplyr that uses . as a placeholder and permits a bare function name.
Older code may write runs %>% nrow, while the native form needs runs |> nrow().
Mean of ratios
A mean of ratios averages separately calculated observation-level ratios, giving each included observation equal weight in that average.
Mean per-run pace weights a short run and a long run equally, unlike the ratio of total time to distance.
Membership test
A membership test uses %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
A minimum group size is a stated eligibility rule excluding groups with too few supporting observations before a comparison or ranking.
Requiring at least 20 recorded café ratings removes any café with fewer ratings from an eligible ranking.
Minimum rank
A minimum rank assigns ties the smallest occupied rank and leaves gaps afterward, so ranks track the positions consumed by tied rows.
Two rows sharing rank 7 under min_rank() are followed by rank 9, not rank 8.
Missing value
A missing value, written NA in R, represents an unknown entry whose ordinary comparisons and arithmetic usually remain unknown.
A run with a missing distance produces an unknown pace even though its time is recorded.

N

Namespace
A namespace identifies a package explicitly in a function call, using 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 means "not a number" and can mark an undefined numeric result, such as the mean after every input value has been removed as missing.
An all-missing distance group has mean NaN with removal, even though its corresponding empty sum is 0.
Native pipe
The 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
An output level specifies what one result row represents, such as one run, one runner-week, or one runner across all included weeks.
A pipeline for each runner's best week first creates runner-week totals and then moves to one maximum per runner.

P

Pace
Pace is time per unit of distance; minutes divided by kilometers gives minutes per kilometer, with smaller values indicating faster movement.
A run that takes 30 minutes for 5 km has a pace of 6 min/km.
Pipeline
A pipeline is a sequence of calls connected so that each step receives the preceding result and carries out the next part of an analysis.
A pipeline for week-3 runs first chooses those observations and then sorts the retained rows by distance.
Placeholder
A placeholder marks where piped input should enter a call; the native _ 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
A random seed fixes the starting state of random-number generation, allowing the same sampling code to be reproduced in the same setup.
Run set.seed(42) immediately before the sample when you want the same random selection again.
Ratio of totals
A ratio of totals divides two accumulated quantities over matching observations, giving a combined measure such as overall time per kilometer.
Overall runner pace divides included minutes by included kilometers, so longer runs have more influence.
Recorded-value count
A recorded-value count measures how many non-missing observations contributed to a particular calculation, showing its actual measured support.
sum(!is.na(distance_km)) reports the number of distances used when a mean removes missing values.
Reproducible analysis
A reproducible analysis records the steps from input data to results so the same procedure can be rerun and its calculations inspected.
Keeping the raw log and saving a descriptive runner summary lets another reader follow the whole calculation.

S

Sampling without replacement
Sampling without replacement chooses rows randomly while allowing each input row to appear at most once in that particular sample.
slice_sample(runs, n = 3) chooses three rows without repetition unless replace = TRUE is supplied.
Selection helper
A selection helper chooses a set of columns by a naming rule, position, or type inside a function that supports tidy selection.
ends_with("_score") selects every column whose name ends in _score without reading its values.
Slice
A slice selects observations by row position or a helper rule, such as first, last, smallest, largest, or randomly chosen rows.
slice(runs, 2:4) keeps positions 2 through 4 in the current order of the table.
Small-group variability
Small-group variability describes the greater movement of an average when it is based on few observations and one value changes or is added.
One café's two-rating average can shift much more with one additional rating than another café's 180-rating mean.
Sort key
A sort key is a column or expression used to order rows; later keys break ties among rows equal on all preceding keys.
In arrange(runs, runner, desc(time_min)), time breaks ties among rows with the same runner name.
Summary statistic
A summary statistic is a value describing a set of observations, such as its total, center, spread, extreme, or size.
A median of 7.5 km for recorded distances describes the center of a running log without retaining individual runs.

T

Table shape
A table shape is its number of rows and columns; comparing expected and observed shapes helps locate a surprising pipeline step.
A runner summary should have one row per runner, while sorting that summary should leave its row count unchanged.
Tibble
A tibble is a modern data frame whose printed view shows table dimensions, column names, column types, and a preview of its rows.
A running log with ten rows and four columns, one of them character, prints as a tibble that shows those details.
Tidy selection
Tidy selection is the column-selection system that interprets names, ranges, helpers, and type tests to choose columns for an operation.
.by = c(runner, week) uses tidy selection to choose grouping columns for one verb.
Tie
A tie occurs when several rows have the same comparison value; extreme-value slice helpers retain cutoff ties unless instructed otherwise.
If a runner's two shortest runs are both 5 km, both survive a request for that runner's single shortest distance with default tie handling.

V

Vectorized calculation
A vectorized calculation applies an expression to corresponding elements of columns, producing rowwise results without a separate call per row.
In time_min / distance_km, each run's time is paired with that same row's distance throughout a log of runs.
Verb
A verb is a dplyr function that performs a table operation, taking data first and returning a new table with the requested changes.
filter(runs, week == 2) uses a row verb to keep only the observations from week 2.

W

Weighted count
A weighted count adds a supplied weight column within each group instead of counting rows; dplyr skips missing weights in this total.
Use wt = distance_km and name = "total_km" to report recorded distance totals by runner.
Window function
A window function calculates a value for each row using other rows or a set of values, without collapsing the table into a summary.
A running distance total uses earlier rows, while a rank compares a run's distance with other values.

#

`.by`
The .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`
The .groups argument controls grouping left after summarize(), including dropping the last level, dropping all levels, or keeping them.
A runner-week summary with .groups = "drop" lets a following share calculation see all summary rows.
`.keep_all`
The .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`
The .keep argument controls which existing columns remain after mutate(), while new and grouping columns remain available.
When mutate() computes pace from distance and time, .keep = "used" shows those inputs beside the pace for a compact checking view.
`add_count()`
The add_count() function appends a group count to each original observation, retaining all input rows for later row-level work.
After add_count(runner), each of a runner's four runs has its runner count recorded as 4.
`all_of()`
The all_of() helper selects columns named in a character vector and stops with an error if any requested name is absent.
Use all_of(cols) when a report cannot be calculated correctly without every column listed in cols.
`any_of()`
The any_of() helper selects the existing columns named in a character vector, skipping requested names that are absent from the table.
In a table without a pace column, any_of(c("runner", "pace")) keeps runner because pace has not been created.
`arrange()`
The 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()`
The 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()`
The case_when() function assigns each row the outcome of its first true condition, using an optional default when no condition matches.
A pace below 5.9 must meet the "fast" branch before the broader below-6.3 "steady" branch.
`count()`
The count() function returns counts by category or combination, temporarily grouping the data and preserving the input's persistent groups.
When three runners log 4, 3, and 3 runs, count(runs, runner) returns three rows with those counts.
`distinct()`
The 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()`
The 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()`
The 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()`
The group_by() function attaches persistent grouping structure to a table so later calculations operate within the specified groups.
Saving a table after group_by(runner) also saves its grouping state for later verbs.
`group_vars()`
The group_vars() function lists a table's persistent grouping columns, returning an empty character vector when there are no groups.
Inspect group_vars(result) before computing a denominator intended to cover the entire result.
`if_else()`
The if_else() function selects between compatible true and false outcomes for each row, with a separate optional outcome for a missing condition.
A distance rule can produce "long", "short", or missing = "unknown" labels in a new column.
`mutate()`
The 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()`
The 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`
The 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()`
The 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()`
The 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()`
The 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()`
The 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()`
The 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()`
The summarize() function reduces each group to one row of named summary values, returning one overall row when the input has no groups.
A runner summary replaces the individual runs with each person's distance total and run count.
`tally()`
The 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()`
The ungroup() function removes persistent grouping from a table, allowing later calculations to use the whole table as one scope.
Call ungroup() before calculating a share whose denominator should include every runner.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started