Joins in R

Joins, Functions and Iteration in R

Combine tables, write your own functions and repeat work in R without copying code. You will check the keys that link tables, choose between left, inner, right and full joins, and catch joins that add or lose rows. Semi and anti joins find matches and gaps, and joins on ranges and closest values handle dates and thresholds. You will turn repeated code into vector, data frame and plot functions, apply them to many columns with across() and to lists and files with purrr's map() functions, and read a whole folder of files into one table. A final part covers the base R subsetting, lists, loops and apply functions you will meet in other people's code.

IntermediateLesson 6 of 7 in Data Analysis with R Course

What you will learn

  1. Identify the keys that connect related tables, add columns from one table to another with the four mutating joins, and control how rows are matched so the joined table has exactly the rows you expect.
    • Identify and check the keys that connect tables
      Recognize primary, foreign, compound and surrogate keys, check that a key really identifies each row, and describe how two tables relate.
    • Add columns with left, inner, right and full joins
      Use the four mutating joins with join_by() to add variables from one table to another, predict which rows each join keeps, and handle key columns with different names and clashing column names.
    • Control row matching and catch join problems
      Predict how many rows a join returns, recognize duplicated and missing keys, state the expected relationship so dplyr checks it, and verify a join before relying on it.
  2. Use filtering joins to keep or drop rows by whether they have a match, and use cross, inequality, rolling and overlap joins when rows should match on conditions other than equal keys.
    • Keep or drop rows with semi and anti joins
      Use semi_join() and anti_join() to filter a table by its matches in another table, find orphan and missing rows, and explain how filtering joins differ from mutating joins.
    • Join on inequalities, closest matches and ranges
      Use cross joins, inequality joins, rolling joins with closest() and overlap joins with between(), within() and overlaps(), and check the extra rows these joins can create.
  3. Turn repeated code into well-named functions with clear arguments and checks, and write functions that work with data frames and plots by passing column names through embracing.
    • Write vector functions with arguments and return values
      Decide when to write a function, build one from repeated code, use arguments with defaults, and write mutate-style and summary-style functions, including anonymous functions.
    • Make functions safe and readable
      Use if and else for choices, stop a function with a clear message when its input is wrong, avoid hidden dependencies on outside variables, and name and style functions so others can read them.
    • Write data frame and plot functions with embracing
      Explain why dplyr and ggplot2 code inside a function needs embracing, choose between data-masking and tidy-selection arguments, and write functions that summarize, select, name and plot columns chosen by the caller.
  4. Apply the same operation to many columns with across(), to the elements of vectors and lists with purrr's map functions, and to many files at once, combining the results into one table.
    • Apply functions to many columns with across()
      Use across() in summarize() and mutate() to apply one or several functions to selected columns, control the output names, filter with if_any() and if_all(), and decide when pivoting is the better tool.
    • Map functions over vectors and lists with purrr
      Use map() and its typed variants to apply a function to each element, iterate over two or more inputs, run functions for their side effects, and combine lists of data frames into one table.
    • Read many files at once and save many outputs
      List files in a folder, read them into one table with read_csv() or map() and list_rbind(), recover information stored in file names, deal with inconsistent or failing files, and write one output per group.
  5. Use base R subsetting, lists, loops and the apply family, which appear throughout older code, help pages and answers online, and connect each tool to its tidyverse equivalent.
    • Select elements of vectors and data frames with [
      Subset vectors with positive, negative, logical and character indices, subset data frames by rows and columns, handle missing values in conditions, and relate [ to filter() and select().
    • Extract single elements with $ and [[ and work with lists
      Pull one column or list element with $ and [[, explain how they differ from [, add and remove columns in base R, and inspect nested lists.
    • Repeat code with for loops and the apply family
      Write for loops with a preallocated output and seq_along(), use lapply(), sapply(), vapply() and tapply(), make quick base R plots, and relate each to the purrr and dplyr tools.

Joins in R study guide

5 chapters

1

Combine tables with keys and mutating joins

Related tables can describe the same observations at different levels: one row per station in one table and one row per daily reading in another. You will identify the columns that link them, choose which unmatched rows should survive and predict how repeated keys affect the result. Explicit matching rules and checks turn a join into a controlled step in an analysis, with a clear reason for every row kept, added or lost.

1.1 Find the columns that identify each row

A join lines up observations from two tables. Before writing it, decide what one row represents in each table. A station table has one row per station; a reading table can have many rows per station because it records several dates.

Build the example tables

Load the tidyverse once before running these examples. It supplies tibble(), dplyr, purrr, readr, stringr and ggplot2.

library(tidyverse)
stations <- tibble(
  station_id = c("S1", "S2", "S3"),
  site = c("harbor", "airport", "hilltop"),
  elevation_m = c(5, 12, 340)
)
readings <- tibble(
  station_id = c("S1", "S1", "S2", "S4"),
  date = as.Date(c("2024-03-01", "2024-03-02",
                   "2024-03-01", "2024-03-01")),
  temp_c = c(18.5, 19.1, -3.2, 25.0)
)

A primary key uniquely identifies a row. Here station_id identifies each station. In readings, the same column is a foreign key: it refers to the station's identifier. Repetition in a foreign key is expected when several observations belong to one station.

A compound key uses several columns together. Neither station_id nor date identifies each reading alone, but their pair does for these data. The intended rule is one reading per station per day. If readings later include several times per day, that pair will no longer be enough.

Check uniqueness and missing values separately
stations |> count(station_id) |> filter(n > 1)
readings |> count(station_id) |> filter(n > 1)
readings |> count(station_id, date) |> filter(n > 1)
stations |> filter(is.na(station_id))

The first check returns no rows: station IDs are unique. The second returns S1 with n = 2; the third returns no rows because each station-date pair occurs once. The last check looks for missing station IDs. A count check alone can overlook a single missing ID, so both checks matter. Repeat them when new rows arrive.

The tables have a one-to-many relationship from stations to readings: one station can have several readings. Viewed from readings to stations, it is many-to-one. A one-to-one relationship allows at most one match on either side. A many-to-many match occurs when repeated keys on both sides pair several rows with several rows.

Keep identifiers tied to the observations

A surrogate key is an artificial identifier. For example, mutate(id = row_number(), .before = 1) gives each current row a number. Another table can store those assigned IDs as foreign keys. Numbering two tables independently does not establish a relationship: the third station and the third reading need not belong together.

Matching columns can have different names, such as station_id and id. Their values must describe the same identifiers and have compatible types. Finally, check that foreign keys have partners. S4 appears in readings but not in stations; that reading is an orphan row. A filtering join will let you inspect it before adding station details.

Key Takeaways

  • A primary key identifies rows; a foreign key refers to those identifiers in another table.
  • Check both repeated values and missing values in a proposed primary key.
  • A compound key works only when the whole combination identifies an observation.
  • Relationship direction matters: stations to readings is one-to-many.
  • Surrogate IDs work across tables only when the assigned identifiers are carried with the observations.

1.2 Choose the rows a mutating join keeps

A mutating join adds columns from a second table, y, to a first table, x. The choice of join determines which unmatched rows survive. Matching still happens row by row, so several matches can produce several output rows.

Add station details to readings

Using the station and reading tables, run:

readings |> left_join(stations, join_by(station_id))

The four reading rows stay. The two S1 readings receive site "harbor" and elevation 5 m; S2 receives "airport" and 12 m. S4 has no station match, so its new site and elevation_m values are NA. For this many-to-one match, the number of rows stays four.

JoinRows retainedResult here
left_join()Every row of xFour readings, including S4
inner_join()Matched rows onlyThree readings; S4 disappears
right_join()Every row of yThree matched readings plus S3
full_join()Every row of both tablesFour readings plus S3

In the right and full joins, S3 has no reading, so its date and temperature are missing. An inner join can silently remove observations; choose it when removing unmatched rows is part of the analysis. A left join keeps all original rows but can increase their number if a row has several partners. A Venn diagram shows surviving keys, not repeated rows.

State the full matching rule

join_by(station_id) means equality on that column. If the station table instead calls its identifier id, use join_by(station_id == id): the left name belongs to x, and the right name to y. Equality joins normally retain the key under the left-hand name. Set keep = TRUE to inspect both input key columns.

For daily rainfall, station alone is insufficient:

rain <- tibble(
  station_id = c("S1", "S1", "S2"),
  date = as.Date(c("2024-03-01", "2024-03-02", "2024-03-02")),
  rain_mm = c(0, 4.2, 1.5)
)
readings |> left_join(rain, join_by(station_id, date))

The added values are 0, 4.2, NA, NA. The S2 rainfall is for March 2, while its reading is for March 1. Matching only station would attach rainfall from the wrong day and could multiply rows.

Read column names and older syntax

Without an explicit specification, dplyr performs a natural join on every shared column name. Two tables might both contain name, with one holding site names and the other staff names. Those are different facts; matching both can prevent valid station matches. Write join_by() in scripts so an added column cannot quietly change the matching rule.

Non-key columns with the same name receive .x and .y. You can make their meaning clearer with suffix = c("_station", "_keeper"). Unexpected date.x and date.y can expose a missing date component in the key.

In base R, merge(readings, stations, by = "station_id", all.x = TRUE) is a left join. Its default is an inner join; all = TRUE requests a full join. Unlike dplyr's mainly left-based row order, merge() sorts by key by default.

Key Takeaways

  • Choose left, inner, right or full joins by deciding which unmatched observations must remain.
  • An inner join drops unmatched rows without a warning by default.
  • List all parts of a compound key in join_by().
  • Explicit keys prevent shared non-key column names from changing a join.
  • Equality joins normally retain the left key; keep = TRUE retains both.
  • Non-key name collisions receive suffixes; merge() sorts by key by default.

1.3 Predict row counts and enforce the match you expect

A successful join call can still produce the wrong table. Check how often each key occurs and state the relationship you expect. Row retention, multiple matches and unmatched keys are separate questions.

Count matches before counting output rows

Every row of x appears once per matching row of y. A left join also keeps each unmatched x row once. Joining stations to readings therefore gives four rows: two for S1, one for S2 and one unmatched S3.

For keys c(1, 2, 2) on both sides, key 1 contributes one row. Each of the two left rows for key 2 pairs with both right rows, contributing four more. The total is five. This many-to-many equality match normally warns; a one-to-many match can increase the row count without warning.

joined <- readings |>
  left_join(
    stations, join_by(station_id),
    relationship = "many-to-one"
  )
nrow(readings)
nrow(joined)

relationship = "many-to-one" requires each left row to match at most one right row. "one-to-many" checks the reverse; "one-to-one" checks both. A violation stops the join. "many-to-many" permits unrestricted matching and suppresses the usual warning; it does not repair a bad key.

Separate three controls
ArgumentWhat it controlsImportant detail
relationshipMaximum matches per rowDoes not require a match to exist
unmatchedUnmatched rows that would be droppedA left join checks y
multipleWhich matches of a left row to returnDefault "all" keeps every match

For readings |> inner_join(stations, join_by(station_id), unmatched = "error"), S4 prevents success because it has no station. A left join with the same setting instead checks for unused station rows: S3 prevents success. The left reading rows already survive a left join, so unmatched does not check their missing partners.

multiple = "first" or "last" selects one of several right-hand matches in their order. It is not a rule for choosing the latest date. If a unique lookup was intended, resolve the repeated key instead of hiding it with one selected match.

Inspect keys that look alike

Missing keys match other missing keys by default. Set na_matches = "never" when two unknown identifiers should not be treated as the same observation. First inspect why the IDs are missing.

Numeric and character keys cannot be joined directly when their types are incompatible. Keep IDs such as "007" as text: converting them to numbers loses the leading zeros, and converting back produces "7". Spaces and case also matter. Use str_trim() and, when identifiers are case-insensitive, str_to_upper() consistently on both tables.

Check the joined result

Before joining, count duplicate lookup keys and inspect missing IDs. Then choose the join and its expected relationship. Compare nrow() before and after, and inspect added columns for NA. A missing site could reflect an unmatched key or an already missing site value in a matched station row. anti_join() identifies missing partners directly, without confusing those two causes.

Key Takeaways

  • For repeated keys, count every left-right pair; a left join also retains unmatched left rows.
  • Use relationship to enforce expected maximum matches.
  • In a left join, unmatched = "error" checks unused right rows.
  • Choosing a first match can conceal a duplicated lookup key.
  • Check missing keys, types, spaces, row counts and missing partners.
2

Filter rows and match on conditions with joins

A second table can answer whether an observation has a partner, which expected observations are missing or which time interval applies. You will use filtering joins for existence checks, then move beyond equality to thresholds, recent dates and ranges. The main decision is what qualifies as a match; boundary values, overlapping ranges and tied lookup values determine whether a row has zero, one or several partners.

2.1 Find matching rows and missing combinations

Sometimes the second table is only a list of rows to keep or investigate. A filtering join uses matches to select rows of x. It adds no columns from y and never duplicates a left-hand row.

Ask whether a partner exists
stations |> semi_join(readings, join_by(station_id))
stations |> anti_join(readings, join_by(station_id))

The semi join returns S1 and S2: both have readings. S1 appears once even though it has two readings. The anti join returns S3, which has none. Compare this with an inner join: an inner join would return three rows, repeat S1 and bring in reading columns.

A semi join answers an existence question. Once a left row has a partner, additional right rows do not change whether that left row is selected. Existing duplicate rows in x remain separate rows; the join does not deduplicate the input.

Choose the direction of the check

Reversing an anti join changes its meaning:

readings |>
  anti_join(stations, join_by(station_id)) |>
  count(station_id)

This finds orphan readings, returning S4 with n = 1. The earlier station-to-reading anti join found unused stations. Both are useful, but they diagnose different gaps. Before a mutating join, an anti join from the main table lists rows that would receive no lookup information in a left join or disappear in an inner join.

To restrict readings to low-elevation stations, first select the relevant station rows:

low <- stations |> filter(elevation_m < 100)
readings |> semi_join(low, join_by(station_id))

This keeps the three readings from S1 and S2. With one key, filter(station_id %in% low$station_id) gives the same selection. A filtering join also handles compound keys and differently named keys directly. Testing each component separately with %in% can admit combinations that never occurred together.

Make absent observations visible

An explicit missing value occupies a cell containing NA. An implicit missing value has no row at all. Looking for is.na(temp_c) cannot find a station-day that was never recorded.

Create the expected station-days, then remove the combinations already present:

days <- tibble(date = as.Date(c("2024-03-01", "2024-03-02")))
expected <- cross_join(stations |> select(station_id), days)
expected |>
  anti_join(readings, join_by(station_id, date))

There are six expected rows: three stations on two dates. Three combinations are present within this set: S1 on both dates and S2 on March 1. The result contains S2 on March 2 and S3 on both dates. The S4 reading does not fill any expected station-day because S4 is not one of these stations.

Choose the expected set from the observation schedule. Here every listed station should report on both days. The anti join checks that schedule; it cannot decide which combinations the schedule should contain.

Key Takeaways

  • semi_join() retains left rows with a partner; anti_join() retains left rows without one.
  • Filtering joins preserve left columns and never multiply left rows.
  • Reverse an anti join to check the other table for missing partners.
  • Find absent combinations by anti joining observed keys from an expected grid.

2.2 Match thresholds, dates and intervals

Equality is only one way to match observations. A non-equi join can find every threshold below a value, the nearest eligible date or overlapping intervals. Choose the condition from the meaning of the match, then check its boundaries and row count.

Start with all eligible thresholds
gusts <- tibble(speed_kmh = c(12.5, 20, 61))
bands <- tibble(
  min_kmh = c(0, 20, 50),
  category = c("light", "moderate", "strong")
)
gusts |> left_join(bands, join_by(speed_kmh >= min_kmh))

The three gusts match one, two and three thresholds, producing six rows. The inequality asks for every qualifying pair. It does not mean "pick the category containing this speed."

A rolling join selects the closest eligible threshold:

gusts |> left_join(
  bands,
  join_by(closest(speed_kmh >= min_kmh)),
  relationship = "many-to-one"
)

The categories are light, moderate and strong. With >=, a speed of 20 includes threshold 20; with >, it excludes it and receives light. closest() chooses a value, not a unique row: two rows at threshold 20 both qualify as closest. The relationship check catches that duplication.

Match the most recent calibration
calibrations <- tibble(
  station_id = c("S1", "S1"),
  cal_date = as.Date(c("2024-01-10", "2024-03-02")),
  offset_c = c(0.2, -0.1)
)
checks <- tibble(
  station_id = rep("S1", 4),
  date = as.Date(c("2024-01-05", "2024-02-20",
                   "2024-03-02", "2024-03-15"))
)
checks |> left_join(
  calibrations,
  join_by(station_id, closest(date >= cal_date)),
  relationship = "many-to-one"
)

Equality keeps calibrations within each station; the rolling condition chooses the latest calibration on or before each reading. The offsets are NA, 0.2, -0.1 and -0.1 °C. January 5 precedes every calibration. Without closest(), later readings match all earlier calibrations and this left join returns six rows.

Compare points and ranges
Helper inside join_by()Match required by default
between(date, start, end)The point lies inside the right interval, including endpoints
within(s, e, lo, hi)The whole left interval lies inside the right interval
overlaps(s, e, lo, hi)The intervals share at least one point

Winter running January 1–February 29 and spring running March 1–May 31 label the four check dates winter, winter, spring, spring. A left join preserves a date outside every interval with missing season information. Overlapping season ranges can attach two labels to one date.

For jobs spanning hours 2–5 and 8–12, with shifts 0–6 and 6–10, overlap matches the first job to the early shift and the second to the late shift. Only the first job lies wholly within its shift.

cross_join(x, y) generates every pair without a matching condition. Three sizes and two colors produce six combinations. Inequality joins can multiply rows without the usual equality-join warning. Inspect gaps, overlaps and tied thresholds, and compare the result with the intended number of matches.

Key Takeaways

  • An inequality join returns every pair satisfying its condition.
  • closest() chooses the closest eligible value; tied lookup rows still give several matches.
  • Combine equality and rolling conditions to keep time matches within the correct group.
  • between() matches a point to a range; within() requires full containment; overlaps() requires shared extent.
  • Default interval endpoints are included.
  • cross_join() returns all pairs; non-equi row multiplication needs explicit checking.
3

Write your own functions

When the same calculation appears in several places, a function gives it a name and a consistent interface. You will turn changing inputs into arguments, return results that fit a transformation or summary and handle special cases before they cause confusing failures. Table and plot functions add another skill: forwarding the caller's column expressions while keeping ordinary options, such as a bin width, as values.

3.1 Turn repeated calculations into vector functions

Repeated code is a useful clue that a task needs a function. Compare the copies: changing inputs become arguments, and the shared calculation becomes the body. A named function gives you one place to fix the calculation.

Name the calculation and its inputs
rescale01 <- function(x) {
  rng <- range(x, na.rm = TRUE)
  (x - rng[1]) / (rng[2] - rng[1])
}
rescale01(c(2, 4, 6, 10))

The function name is rescale01, its argument is x, and its body is the code inside braces. The range runs from 2 to 10, so the width is 8. Subtracting 2 gives 0, 2, 4 and 8; dividing by 8 gives 0, 0.25, 0.5 and 1.

The last expression is the return value. Assigning the call to an object saves that result. The local variable rng belongs to the function call. It does not become a new global variable. Use return(value) when you need to finish a call early.

Match the result to the surrounding verb

A mutate function returns a vector the same length as its input. For example:

z_score <- function(x) {
  (x - mean(x, na.rm = TRUE)) / sd(x, na.rm = TRUE)
}
z_score(c(2, 4, 6, 8))

The mean is 5 and the sample standard deviation is about 2.582. The results are approximately -1.162, -0.387, 0.387 and 1.162. A call such as mutate(temp_z = z_score(temp_c)) therefore adds one value per row.

A summary function returns one value. The coefficient of variation divides the standard deviation by the mean:

cv <- function(x, na.rm = FALSE) {
  sd(x, na.rm = na.rm) / mean(x, na.rm = na.rm)
}
cv(c(2, 4, 6, 8))

This returns about 0.516 and fits inside summarize(). The argument na.rm has a default, so callers can omit it. Both internal functions receive the caller's setting. cv(c(2, 4, NA, 8)) gives NA; with na.rm = TRUE, the mean is about 4.667, the standard deviation about 3.055 and the result about 0.655.

Put the data argument first and options after it. Arguments can be matched by position or name. For add <- function(x, y = 1) x + y, add(5) returns 6, while add(y = 3, x = 5) returns 8. Naming detail arguments makes their purpose clear.

Use short functions where they are needed

An anonymous function has no stored name. \(x) x^2 is shorthand for function(x) x^2. It is useful when passing a small calculation to map() or across(). Older code may write ~ .x^2 for the same calculation.

Test normal and unusual inputs before reusing a function. rescale01(c(2, 4, NA, 10)) keeps the missing element and gives 0, 0.25, NA, 1. Constant input such as c(3, 3, 3) has zero range width and produces NaN. Infinite input also needs attention: c(2, 4, Inf) gives 0, 0, NaN. Adding finite = TRUE to range() changes those results to 0, 1, Inf; it changes how the range is computed, not the infinite input itself.

Key Takeaways

  • Turn the parts that vary across copied code into arguments.
  • A function returns its last evaluated expression unless an earlier return() ends it.
  • Mutate functions return row-length vectors; summary functions return one value.
  • Default options must be passed through to the calculations that use them.
  • Test missing, constant and infinite inputs as well as ordinary values.

3.2 Check inputs and make dependencies visible

A reusable function needs clear behavior when its input is wrong or unusual. Validate the inputs that could cause a confusing failure or a silently wrong result. Keep the checks close to the start of the function.

Use one condition for a branch

if chooses one branch for the whole function call. Its condition must be one non-missing logical value.

sign_label <- function(x) {
  if (x > 0) "pos" else "not pos"
}
sign_label(3)

This returns "pos". A vector such as c(1, -1) produces two conditions and cannot control one if. An NA condition also cannot select a branch. Use if_else(x > 0, "pos", "not pos") for element-by-element choices; with c(1, -1, NA), it returns "pos", "not pos", NA. Use case_when() for several vectorized conditions.

Inside a scalar check, && and || combine single conditions and can stop evaluating once the answer is known. The operators & and | combine logical vectors element by element.

Fail clearly or handle a special case
double_it <- function(x) {
  if (!is.numeric(x)) {
    stop("`x` must be numeric, not ", class(x)[1])
  }
  x * 2
}

Numeric input produces doubled values. Text input stops with a message identifying the expected type. stopifnot(is.numeric(x)) is a shorter alternative with an automatically constructed message. A check should reveal what the caller must change.

An early return handles a valid special case without nesting the main calculation:

safe_ratio <- function(a, b) {
  stopifnot(is.numeric(a), length(a) == 1L,
            is.numeric(b), length(b) == 1L,
            !is.na(a), !is.na(b))
  if (b == 0) return(NA_real_)
  a / b
}

The function returns 2 for safe_ratio(6, 3) and a missing numeric value for safe_ratio(1, 0). The input checks make the scalar condition valid. Without a length check, a vector denominator would still break if even if it were numeric.

Pass changing values as arguments

R uses lexical scoping: a name absent from the arguments and local body is sought in the environment where the function was defined.

offset <- 10
add_offset <- function(x) x + offset
add_offset(1)

The result is 11, but changing the global offset changes later results. A clearer interface is add_offset <- function(x, offset) x + offset. The caller now supplies the dependency directly, and the call records which offset was used.

Give functions verb names such as read_station_file() or compute_cv(). Use nouns for arguments, snake_case for multiword names, and avoid hiding familiar names such as mean, c or T. Put spaces around assignment and arithmetic operators, indent the body by two spaces, and put the closing brace on its own line.

Keep each function focused. Several small functions can express the steps of a longer task. Store them near the top of a script or load them with source(). To diagnose a failure, assign a small input to the argument names and run the body line by line until the result first differs from what you expect.

Key Takeaways

  • if requires one non-missing logical value; vectorized choices need a vectorized function.
  • Use clear input checks before the main calculation.
  • Early returns keep special cases separate from the main path.
  • Pass changing external values as arguments so calls reveal their dependencies.

3.3 Pass columns into table and plot functions

A function that calls dplyr must distinguish a column supplied by the caller from an ordinary value supplied as an option. Embracing, written {{ }}, forwards a caller's column expression into a tidyverse operation.

Forward an unquoted column

Use this small table:

temps <- tibble(
  site = c("harbor", "harbor", "hilltop", "hilltop", "hilltop"),
  temp_c = c(18, 20, 6, 8, NA),
  rain_mm = c(0, 2.5, 10, NA, 4)
)
grouped_mean <- function(df, group_var, mean_var) {
  df |>
    group_by({{ group_var }}) |>
    summarize(mean = mean({{ mean_var }}, na.rm = TRUE),
              .groups = "drop")
}
temps |> grouped_mean(site, temp_c)

The result has harbor with mean 19 °C and hilltop with mean 7 °C. The caller supplies site; embracing passes that column expression into group_by(). Without it, dplyr looks for a column literally named group_var and the call fails. Using rain_mm as the measurement gives means 1.25 and 7 mm.

Pass temp_c without quotes. The string "temp_c" is text, not the numeric column in this interface. Taking its mean produces missing results and a warning. Ordinary options such as na.rm or a histogram's binwidth remain ordinary arguments without embracing.

Know what the receiving argument expects

Data masking lets calculations refer to column names directly. filter(), mutate(), summarize() and group_by() use it. Tidy selection chooses columns with names, positions or helpers; select() and the .cols argument of across() use it. Help pages mark the two kinds of argument.

select_cols <- function(df, cols) {
  df |> select({{ cols }})
}
temps |> select_cols(starts_with("t"))

This returns the temperature column. To put a tidy selection into a data-masking operation, use pick():

count_missing <- function(df, group_vars, x_var) {
  df |>
    group_by(pick({{ group_vars }})) |>
    summarize(n_miss = sum(is.na({{ x_var }})),
              .groups = "drop")
}
temps |> count_missing(c(site), temp_c)

The missing counts are 0 for harbor and 1 for hilltop. pick() makes c(site) a column selection, not a calculation that combines column values.

Create useful names and plots

Use := to construct an output name from the supplied column:

mean_column <- function(df, var) {
  df |> summarize("mean_{{ var }}" :=
                    mean({{ var }}, na.rm = TRUE))
}
mean_column(temps, temp_c)

The output column is mean_temp_c, with value 13. An ordinary = cannot perform this name injection.

Plot functions embrace inside aes() in the same way:

histogram <- function(df, var, binwidth = NULL) {
  ggplot(df, aes(x = {{ var }})) +
    geom_histogram(binwidth = binwidth) +
    labs(title = rlang::englue("A histogram of {{var}}"))
}
histogram(temps, temp_c, binwidth = 1)

The function returns a plot object. The column expression goes into aes(), the numeric option goes into the layer, and englue() turns the supplied expression into title text.

Key Takeaways

  • Embrace caller-supplied columns with {{ }} inside dplyr operations or aes().
  • Keep ordinary options as ordinary arguments.
  • Data masking evaluates calculations; tidy selection chooses columns.
  • Use pick() to supply a column selection within a data-masking operation.
  • Use := for an injected output name and englue() for expression-based text.
4

Repeat work across columns and files with iteration

One well-tested function can handle many columns, list elements or files. You will choose iteration tools from the shape of the input and the result: columns in a table, one scalar per list element, whole tables to combine or files to write. Source names and explicit output types help you trace the results. A folder import brings these ideas together by testing one reading task before repeating it across every path.

4.1 Apply a calculation across selected columns

When several columns need the same treatment, across() keeps the calculation in one place. It has two main inputs: a column selection and a function. The surrounding verb determines whether you transform rows or produce summaries.

Select columns, then supply the function
df <- tibble(grp = c("x", "x", "y"),
             a = c(1, NA, 3), b = c(4, 5, NA))
df |> summarize(across(c(a, b), \(x) mean(x, na.rm = TRUE)))

The means are 2 and 4.5. Without removing missing values, both would be NA. The anonymous function holds the option na.rm = TRUE beside the calculation that uses it; passing that option through the older across(..., na.rm = TRUE) form is deprecated.

The first argument is .cols, a tidy selection: a:b, starts_with("temp"), where(is.numeric) or everything(). The second is .fns. Supplying only a function in the first position makes dplyr try to interpret it as a selection.

Apply several functions and name the results
df |> summarize(across(
  where(is.numeric),
  list(mean = \(x) mean(x, na.rm = TRUE),
       n_miss = \(x) sum(is.na(x))),
  .names = "{.col}_{.fn}"
))

The values are a_mean = 2, a_n_miss = 1, b_mean = 4.5 and b_n_miss = 1. The names combine the input column and named function. Changing the pattern to "{.fn}_{.col}" gives mean_a, n_miss_a and so on.

Within mutate(), the default names replace selected columns:

df |> mutate(across(a:b, \(x) coalesce(x, 0),
                     .names = "{.col}_filled"))

Here the naming pattern instead creates extra columns, preserving the originals. a_filled holds 1, 0, 3; b_filled holds 4, 5, 0. Omitting .names would replace a and b in place.

Reduce several tests to one row condition

if_any() and if_all() combine column tests for filter():

df |> filter(if_any(a:b, is.na))
df |> filter(if_all(a:b, \(x) !is.na(x)))

The first keeps rows 2 and 3 because either measurement is missing. The second keeps only row 1 because both measurements are present. Using across() directly in filter() is deprecated; these helpers produce the single logical vector that row filtering needs.

Respect groups and result shape

After group_by(grp), summarize(across(everything(), \(x) sum(!is.na(x)))) counts present values within each group. Group x has counts 1 and 2; group y has 1 and 0. Grouping columns are handled by the verb and are not selected by across(). A mean after removing every value returns NaN, so a grouped mean for b in group y is not zero.

A wrapper can embrace a selection: summarize_means <- function(df, cols) df |> summarize(across({{ cols }}, \(x) mean(x, na.rm = TRUE)), n = n()). Existing groups are respected when the function is called.

Choose output shape deliberately. across() keeps one column per variable or variable-function pair. pivot_longer(a:b, names_to = "var") followed by grouping on var yields the same overall means as rows. That long format is often easier to plot or use for calculations that relate measurements stored in separate columns.

Key Takeaways

  • Give across() a column selection first and a function second.
  • Put extra calculation options inside an anonymous function.
  • Named functions and .names control output column names.
  • if_any() and if_all() combine column tests for row filtering.
  • Grouped calculations operate within groups and exclude grouping columns from selection.
  • Choose wide output with across() or long output by pivoting to suit the next step.

4.2 Map a function over inputs and choose its output type

map() repeats a function for each element of a vector or list. Each call receives one element, and the result contains one output element per input. Choosing the output container is part of choosing the right mapping function.

Start with the return shape
map(1:3, \(x) x^2)
map_dbl(c(4, 9, 16), sqrt)

The first returns a list holding 1, 4 and 9. The second returns a numeric vector holding 2, 3 and 4. Use a list for outputs such as tables, plots or vectors of several values. A typed variant requires every call to produce one compatible value.

FunctionResult
map()A list
map_dbl()A double vector
map_int()An integer vector
map_chr()A character vector
map_lgl()A logical vector
map_vec()A vector with a common type, including dates

map_int(1:3, \(x) x / 2) fails because 0.5 cannot be stored as an integer without loss. map_dbl() handles 0.5, 1 and 1.5. Conversely, even map_dbl() cannot store both the minimum and maximum from each input as one scalar. Use map() for those two-value results.

Input names are preserved. map_dbl(c(a = 4, b = 9), sqrt) returns named values a = 2 and b = 3. A data frame is a list of columns, so mapping over selected numeric columns applies the function once per column. For temps, column means after removing missing values are 13 °C and 4.125 mm.

Pair inputs without crossing them
map2_dbl(c(1, 2, 3), c(10, 20, 30), \(a, b) a * b)
pmap_dbl(list(a = c(1, 2), b = c(3, 4), c = c(5, 6)),
         \(a, b, c) a + b + c)

map2_dbl() pairs corresponding positions, giving 10, 40 and 90. pmap_dbl() takes one value from each listed input for each call, giving 9 and 12. It does not compute every possible combination. imap() also passes an element's name, or its position when unnamed, so a function can label its result.

Use walk() or walk2() when the purpose is a side effect: printing, saving a plot or writing a file. They run the function and return the input invisibly; collecting the function's return values is unnecessary.

Combine table results deliberately
list(a = tibble(x = 1), b = tibble(x = 2)) |>
  list_rbind(names_to = "src")

list_rbind() stacks tables by rows and records list names as "a" and "b" in src. list_cbind() places tables side by side. Current code uses map() followed by a binding step; map_dfr() and map_dfc() are superseded.

For split-apply-combine, split(temps, temps$site) makes one table per site. Mapping a mean function gives harbor = 19 and hilltop = 7. A grouped summary is simpler for one number per group, while a list is useful when groups produce whole plots or tables.

When a call fails, purrr identifies the input position. For list(1, "a") |> map(\(x) x + 1), the second input fails because text cannot be added to a number. Extract that element and test the function on it alone; changing the mapper cannot fix an invalid calculation.

Key Takeaways

  • map() returns a list; typed variants require one compatible value from each call.
  • map2() pairs positions, pmap() handles several inputs, and imap() supplies names or positions.
  • Use walk() for side effects.
  • Bind table results with list_rbind() or list_cbind() after mapping.
  • Inspect the element named by an indexed map error.

4.3 Import a folder and keep track of each file

A folder of files is a collection of inputs for one reading task. First make the paths explicit. Then decide whether the files can share one read operation or need a function that cleans each file separately.

Discover the inputs and retain their source
paths <- list.files("data", pattern = "[.]csv$", full.names = TRUE)
all_readings <- read_csv(paths, id = "file")

[.]csv$ matches names ending in ".csv". full.names = TRUE keeps the folder in each path. Without it, a bare file name is interpreted relative to the working directory, which may be elsewhere.

For files with the same columns, read_csv() can read the entire path vector. A file containing two readings and another containing three produce five rows. The file column records the source path. Column names must be consistent; type guessing considers the files together, so text such as "n/a" can make an intended numeric column become character.

The general pattern reads one file per call:

results <- paths |>
  set_names(basename) |>
  map(read_csv)
all_readings <- results |> list_rbind(names_to = "file")

Here the source column contains file names because basename() supplied the list names. The same structure works with other readers, including readxl::read_excel().

Recover values stored in names

If the observation year appears only in "readings-2023.csv", turn it into data:

all_readings <- all_readings |>
  mutate(year = as.integer(str_extract(file, "\\d{4}")))

The regular expression extracts four digits and as.integer() converts the extracted text. parse_number("readings-2023.csv") gives -2023: it reads the hyphen as a negative sign.

Clean one file before combining many

list_rbind() aligns columns by name. Files using temp_c and temperature create two separate columns with missing cells; they do not become one measurement column. A numeric temp_c in one file and character temp_c in another can prevent binding.

Inspect headers with map(paths, \(p) names(read_csv(p, n_max = 0))). Write a read_and_clean() function that reads one file, gives its columns consistent names and converts its values to the intended types. Test one file from each layout, then map that function once and bind the results.

To continue past errors, wrap the reader:

safe_read <- possibly(\(p) read_csv(p), otherwise = NULL)
results <- paths |> set_names(basename) |> map(safe_read)
failed <- map_lgl(results, is.null)
names(results)[failed]
all_readings <- list_rbind(results, names_to = "file")

NULL marks an error, and list_rbind() skips those elements. Inspect the failed names before treating the combined table as complete. Parsing warnings can still return a table; possibly() substitutes only when the reader errors.

Save the combined table or one output per group

write_csv(all_readings, "readings-all.csv") saves the cleaned result for later analysis. For one file per station:

by_site <- all_readings |>
  group_nest(station_id) |>
  mutate(path = str_glue("site-{station_id}.csv"))
walk2(by_site$data, by_site$path, write_csv)

Each nested table is paired with its own path. To save a list of plots, pair plots and paths with walk2() and call ggsave(path, p, width = 15, height = 10, units = "cm") inside the function.

Key Takeaways

  • List full paths and retain source names when combining files.
  • Consistent columns allow a multi-file read_csv() call.
  • Extract year digits before converting file-name text to a number.
  • Clean differing names and types inside a function for one file.
  • possibly() can replace errors with NULL; inspect failures before binding.
  • Use walk2() to pair each output object with its destination path.
5

Read and write base R code

Base R code appears in help pages, older scripts and many analysis functions. You will read its indexing operators, distinguish a list from the element inside it and follow a loop from its allocated output to its final result. Connections to dplyr and purrr make the syntax easier to recognize, while examples with missing values and empty inputs show where apparently similar forms behave differently.

5.1 Select values and rows with base R indexing

Base R uses [ to select parts of an object. An index describes the parts to retain or remove. For vectors it can contain positions, logical values or names; for data frames you can specify rows and columns separately.

Read vector indices from left to right
x <- c(10, 20, 30, 40, 50)
x[c(1, 3)]
x[c(1, 1, 2)]
x[-2]
x[x > 25]

Positions start at 1. The results are 10 and 30; 10, 10 and 20; all values except 20; and 30, 40 and 50. Repeated indices repeat values, and the index order determines the result order. Negative positions remove elements. Positive and negative positions cannot be mixed, apart from zero.

x[0] is an empty numeric vector, while x[6] is NA because that position lies beyond the end. Named vectors also accept character indices. For xn <- c(a = 1, b = 2, c = 3), xn[c("c", "a")] returns c = 3 followed by a = 1.

Handle missing logical results
y <- c(5, NA, 8)
y[y > 6]
y[which(y > 6)]
y[!is.na(y)]

The comparison produces FALSE, NA, TRUE. Logical indexing therefore returns NA and 8: the unknown condition creates an unknown selected value. which() retains only positions that are TRUE, so the second call returns just 8. The final call removes missing inputs and returns 5 and 8.

This matters when translating dplyr code. filter() keeps rows where a condition is TRUE and drops both FALSE and NA. A direct base logical index retains a missing output row for an NA condition.

Give data frames rows, then columns
dfb <- data.frame(id = 1:3, temp_c = c(18, NA, 25))
dfb[2:3, c("id", "temp_c")]
dfb[which(dfb$temp_c > 20), , drop = FALSE]
dfb[, "temp_c", drop = FALSE]

The first call selects rows 2 and 3 and both named columns. The second returns only the row with 25 °C, matching filter(temp_c > 20). An empty slot means all rows or all columns in that dimension.

SelectionBase data.frameTibble
df[, "temp_c"]A vectorA one-column tibble
df[, "temp_c", drop = FALSE]A one-column data frameA one-column tibble

Use drop = FALSE when later code requires a table even after selecting one column. dfb[order(dfb$temp_c), ] puts rows in temperature order, 18, 25, NA; order() places missing values last by default. This is the base counterpart of arranging rows.

Avoid the empty-removal trap

It is tempting to drop matches with x[-which(condition)]. If no values meet the condition, which() returns an empty integer vector. Negating it is still empty, so subsetting selects nothing.

With x <- c(5, 6, 7), x[-which(x > 10)] wrongly discards everything for the intended task. x[x <= 10] keeps all three values. Prefer a direct logical condition for exclusion, and account for missing values when building that condition.

Key Takeaways

  • Positive indices select, negative indices exclude, and logical indices retain TRUE positions.
  • Repeated indices repeat values; character indices select named elements.
  • Logical NA indices create missing output; which() keeps only TRUE positions.
  • Data frame indices are rows first, columns second; drop = FALSE preserves table shape.
  • Negating an empty which() result selects no values.

5.2 Extract one element and inspect nested lists

A list can hold elements of different types and lengths, including tables, plots and other lists. A data frame is a list whose elements are columns. The distinction between selecting a smaller container and extracting its contents explains many base R operations.

Keep the container or take its contents
l <- list(a = 1:3, b = "text", c = list(d = 4))
l[1]
l[[1]]
l$c$d

l[1] is a list with one element, named a. l[[1]] is the integer vector 1, 2, 3 itself. The last expression extracts the nested list c and then its element d, returning 4.

Think of [ as handing you a smaller box and [[ as opening the box to retrieve one item. class(l["a"]) is "list", while class(l[["a"]]) is "integer". Arithmetic intended for a numeric element will fail if you pass the surrounding list instead.

The explicit nested form is l[["c"]][["d"]]. At each step, inspect whether you have a list, a table or the final vector. str(l) shows all three elements and the extra level inside c; str(l[1]) shows a one-element list. This is useful for results from map() or imported JSON.

Extract a column by a literal or stored name

Using dfb <- data.frame(id = 1:3, temp_c = c(18, NA, 25)):

dfb$temp_c
dfb[["temp_c"]]
var <- "temp_c"
dfb[[var]]

All three extraction calls return the temperature vector 18, NA, 25. In a dplyr pipeline, pull(temp_c) serves the same purpose. In contrast, dfb$var searches for a column literally named "var" and returns NULL here. It does not read the string stored in the variable.

Use [[ inside functions and loops when the column name changes. The default name lookup is exact. The base $ operator can partially match: dfb$te finds temp_c because no other column begins with "te". A later column with the same prefix can change that behavior. A tibble requires the full name and warns when $ requests an unknown column.

Replace and remove elements deliberately
dfb$double <- dfb$temp_c * 2
dfb[["temp_k"]] <- dfb$temp_c + 273.15
dfb$double <- NULL

The first call adds 36, NA, 50. The second adds kelvin temperatures 291.15, NA, 298.15. Assigning NULL removes the double column; it does not fill that column with missing values. For a list, the same assignment removes the named element.

Missing requests do not all behave alike. In the three-element list, l[[4]] errors because position 4 is outside the list. l$z returns NULL. A tibble column selection such as tb[, "zz"] errors when that column does not exist. Inspect names and structure when a result is unexpectedly empty; a silent NULL can travel farther through a script than an immediate error.

Key Takeaways

  • [ returns a smaller list; [[ extracts one element itself.
  • Use [[var]] when a column name is stored in var.
  • Base $ can partially match names; [[ matches exactly by default.
  • Assigning NULL removes a column or list element.
  • Use str() to inspect nesting before extracting deeply stored values.

5.3 Build loops and recognize the apply family

A for loop makes repeated work explicit. Plan its output, choose the positions to visit and write a body that handles one position. This is useful when a step depends on previous results or when you need to read code written without purrr.

Allocate once and fill one position per pass
v <- c(4, 9, 16)
out <- vector("double", length(v))
for (i in seq_along(v)) {
  out[i] <- sqrt(v[i])
}
out

The output starts with room for three doubles. On each pass, i selects one input and the same output position. The completed vector holds 2, 3 and 4.

seq_along(v) is safe for empty inputs: it produces no positions and the body never runs. 1:length(v) gives c(1, 0) when the length is zero, causing two unwanted passes. Growing out with repeated concatenation also works for nonempty input, but repeatedly allocating and copying larger results is inefficient. Appending sqrt(v) instead of sqrt(v[i]) adds the entire set of roots on every pass.

For tables, allocate a list and fill each element with [[:

files <- vector("list", length(paths))
for (i in seq_along(paths)) {
  files[[i]] <- read_csv(paths[[i]])
}
all_rows <- list_rbind(files)

files[i] selects a sublist, whereas files[[i]] identifies the slot whose contents should be the whole table. Assigning a multi-column table through the wrong form can retain only part of it and produce a warning. Base code often combines compatible tables with do.call(rbind, files).

Recognize when steps depend on each other

For three successive increases of 10%, begin at 100 and update the current value on each pass. The successive values are 110, 121 and 133.1. Each uses the previous result. A loop expresses this dependency directly; mapping independent multiplications of 100 would give 110 three times.

For independent tasks, the apply family gives shorter forms:

FunctionResult behavior
lapply(X, FUN)Always a list, like map()
sapply(X, FUN)Tries to simplify to a vector or matrix
vapply(X, FUN, FUN.VALUE)Checks the requested result shape and type
tapply(X, INDEX, FUN)Summarizes a vector by groups

lapply(1:3, \(x) x * 10) returns a list holding 10, 20 and 30. sapply(list(1:2, 3:4), range) returns a two-row matrix, but sapply(list(), length) returns an empty list. Use vapply(df, is.numeric, logical(1)) when each column must yield one logical value.

Connect base tools to familiar tasks

To transform numeric columns in a table, first identify them with num_cols <- vapply(df, is.numeric, logical(1)). Then assign lapply(df[, num_cols, drop = FALSE], \(x) x * 2) back to df[, num_cols]. This combines selection and columnwise iteration, much like mutate(across(where(is.numeric), ...)).

tapply(temps$temp_c, temps$site, mean, na.rm = TRUE) returns harbor = 19 and hilltop = 7, corresponding to a grouped mean. For a quick visual check, hist(temps$temp_c) draws a histogram and plot(x, y) draws a scatterplot of numeric vectors. Base plots give immediate views; ggplot2 supplies the layered approach already used for customized plots.

Key Takeaways

  • A loop needs an output, a sequence and a body that handles the current element.
  • Preallocate output and use seq_along() so empty inputs behave correctly.
  • Use [[ to store a complete table in one list element.
  • Use a loop when steps depend on previous results.
  • lapply() returns a list; sapply() simplifies; vapply() checks an output template.
  • tapply() computes grouped summaries; base graphics provide quick views.

Joins in R examples

5 Walkthroughs

1

Attach station details without losing readings

14 steps
Check keys, trace retained rows and enforce a many-to-one lookup.
  1. 1
    IntroductionPlan the result before joining

    A station lookup has one row per station, while a reading table has one row per station per day. The aim is to add site details without losing any readings or repeating their temperatures, which depends on this many-to-one relationship.

    Follow one join from key checks (does a primary key really identify one lookup row?) to its output. We will use stations S1, S2 and S3, with reading IDs S1, S1, S2 and S4. The repeated S1 and unknown S4 make two different checks necessary.

  2. 2
    ExplanationRead the two row meanings

    In stations, station_id is a primary key: it identifies one station row. In readings, it is a foreign key that refers to the station lookup.

    S1 occurs twice in readings because the dates differ. That repetition is expected. The pair station_id and date identifies each daily reading, while station alone does not. The relationship is many-to-one from readings to stations.

  3. 3
    ExampleTest both key requirements

    Check the lookup before joining:

    stations |> count(station_id) |> filter(n > 1)
    stations |> filter(is.na(station_id))
    

    Both should return no rows. The first finds repeated identifiers; the second finds missing ones. One missing ID could have count one, so uniqueness alone does not establish a usable primary key. The checks apply to the current data and must be repeated after updates.

  4. 4
    ChallengeIs a reading ID unique?

    A reading table contains station-day pairs S1–March 1, S1–March 2 and S2–March 1. Can station alone identify a reading? What combination works for these rows?

    ---reveal---

    Station alone fails because S1 appears twice. Station plus date identifies the three rows. Date alone also fails because March 1 appears for both stations. The combination expresses the intended one-reading-per-station-per-day rule.

  5. 5
    ExampleTrace a left join
    readings |> left_join(stations, join_by(station_id))
    

    Both S1 readings receive "harbor" and elevation 5 m. S2 receives "airport" and 12 m. S4 has no partner, so it stays with missing site and elevation.

    The result has four rows because every reading has zero or one station partner. A left join guarantees retention of left rows; this unique lookup also keeps their count unchanged.

  6. 6
    ConnectionChanging the join changes coverage

    An inner join keeps the three matched readings and drops S4. A right join keeps the three matched readings plus station S3, with missing date and temperature. A full join keeps both unmatched observations and returns five rows.

    Choose from the observations the analysis must retain. The extra S3 row describes a station without a reading, while S4 describes a reading without station details.

  7. 7
    TipMake keys and column origins explicit

    If the lookup calls its key id, write join_by(station_id == id). Equality joins normally keep the left key; keep = TRUE lets you inspect both input keys.

    For station-day data, include the date as well. Shared non-key column names receive .x and .y suffixes. Unexpected date.x and date.y are a reason to check whether date was omitted from a compound key.

  8. 8
    ChallengeKeep every station and every reading

    With station IDs S1, S2 and S3 and reading IDs S1, S1, S2 and S4, how many rows should a full join produce? Explain the unmatched rows.

    ---reveal---

    Five rows: two matched S1 readings, one matched S2 reading, the unmatched S4 reading and the unmatched S3 station. S4 lacks site details, while S3 lacks reading details. Counting only distinct keys would miss the two separate S1 observations.

  9. 9
    ExamplePredict a repeated-key result

    Suppose a key appears twice in a left table and three times in a right table. Each left row matches all three right rows, producing six row pairs for that key.

    This is why a plausible joined table can inflate a later total. The join repeats the measurements while attaching lookup information. Count the partners for each input row instead of assuming one output row per distinct key.

  10. 10
    ExplanationEnforce the lookup relationship
    readings |> left_join(
      stations, join_by(station_id),
      relationship = "many-to-one"
    )
    

    The relationship requires at most one station partner per reading. Duplicate lookup rows that match a reading cause an error. The check does not require every reading to have a partner: S4 still survives with missing lookup fields. Match limits and match existence are separate checks.

  11. 11
    Key InsightKnow which rows unmatched checks

    In a left join, all left rows survive. Therefore unmatched = "error" checks unused right rows, because those are the observations the join would otherwise drop.

    Here S3 triggers that check; S4 does not. To find readings lacking station details, inspect unmatched readings directly. Setting a relationship or checking unused lookup rows cannot establish that every foreign key has a partner.

  12. 12
    ChallengeCatch the repeated lookup

    A lookup accidentally contains two S1 station rows. What happens to the two S1 readings in a default left join? What does a many-to-one check change?

    ---reveal---

    Each reading matches both lookup rows, so the two readings produce four S1 rows. A many-to-one check stops with an error because each reading has two partners. Selecting the first match would hide the repeated lookup instead of resolving its cause.

  13. 13
    ChallengeAudit a join with the expected row count

    A many-to-one left join returns four rows, matching the reading count, but one site is missing. Has every reading found a station? How can you find out?

    ---reveal---

    The row count cannot settle this: a left join retains an unmatched reading once. Run readings |> anti_join(stations, join_by(station_id)) to identify missing partners. A matched station might itself have a missing site, so inspecting site values alone is also insufficient.

  14. 14
    RecapUse three separate join decisions

    Decide what identifies an observation, which unmatched observations must remain and how many partners each row may have. Those choices determine the keys, join type and relationship check.

    For the station lookup, retain readings with a left join and enforce many-to-one matches. Inspect missing partners directly, then compare row counts and added fields. An unchanged count is useful evidence about shape, not a complete check of coverage.

2

Find gaps and choose time-based matches

13 steps
Use existence checks, expected grids and rolling or interval conditions.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionChoose what a match should answer
  2. 2
    ExampleSelect stations that reported
  3. 3
    ExplanationReverse the gap check carefully
  4. 4
    ChallengeKeep a requested pair together
  5. 5
    ExampleFind missing rows with an expected grid
  6. 6
    ExampleCount every eligible threshold
  7. 7
    ExampleChoose the closest eligible threshold
  8. 8
    TipCheck ties at the chosen value
  9. 9
    ConnectionUse the same rule for earlier dates
  10. 10
    ExplanationDistinguish overlap from containment
  11. 11
    ChallengeChoose a calibration at the boundary
  12. 12
    ChallengeCheck both reporting gaps and labels
  13. 13
    RecapTranslate the question into a match rule
3

Build and test a reusable analysis function

17 steps
Move from a vector calculation to checked arguments and column-aware wrappers.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake one calculation reusable
  2. 2
    ExplanationSeparate inputs from the body
  3. 3
    ExampleWork through the returned vector
  4. 4
    TipForward options into each calculation
  5. 5
    ChallengeTest the zero-width case
  6. 6
    ExplanationKeep branching scalar
  7. 7
    ExampleValidate before handling a special case
  8. 8
    ConnectionMake an offset part of the interface
  9. 9
    ChallengeDiagnose a vector denominator
  10. 10
    ExplanationForward a column expression
  11. 11
    ExampleBuild a grouped-mean wrapper
  12. 12
    Key InsightSelection and calculation need different interpretation
  13. 13
    ExampleName the result from the supplied column
  14. 14
    ConnectionReturn a plot built from the same column
  15. 15
    ChallengeSeparate a column from an option
  16. 16
    ChallengeReview a function before mapping it
  17. 17
    RecapTest the interface as well as the formula
4

Repeat one task across columns and files

19 steps
Choose columnwise, list and file iteration by the result each call produces.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDecide what one call should receive
  2. 2
    ExampleCompute two means with one definition
  3. 3
    ExplanationName multiple calculations
  4. 4
    ChallengeKeep the row with both values present
  5. 5
    Key InsightGroups change the input to each mean
  6. 6
    ExampleChoose a container for each result
  7. 7
    ConnectionA table is a list of columns
  8. 8
    ExplanationPair inputs for each call
  9. 9
    ChallengeStore two values from every group
  10. 10
    ExampleBind returned tables and keep their names
  11. 11
    TipUse return values only when you need them
  12. 12
    ExampleList and read the folder
  13. 13
    ExampleUse one cleaning function for one path
  14. 14
    TipExtract a year before parsing it
  15. 15
    ChallengeA combined table has two temperature columns
  16. 16
    ExplanationKeep failures visible when continuing
  17. 17
    ExamplePair each saved table with a path
  18. 18
    ChallengeCheck a folder pipeline before reporting totals
  19. 19
    RecapChoose iteration from one call and its result
5

Read a base R script without losing its structure

16 steps
Trace vector indices, nested elements, preallocated loops and apply results.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow values and their containers
  2. 2
    ExampleSelect by position, exclusion or condition
  3. 3
    Key InsightAn unknown index leaves unknown output
  4. 4
    ExampleKeep a selected column as a table
  5. 5
    ChallengeRemove no values correctly
  6. 6
    ExplanationOpen one list element
  7. 7
    TipUse a stored name with double indexing
  8. 8
    ChallengeSelect a table stored inside a list
  9. 9
    ExampleAllocate, visit and store
  10. 10
    ExplanationMake empty input a normal case
  11. 11
    ConnectionRecognize independent and dependent steps
  12. 12
    ExplanationRead the output promise of an apply call
  13. 13
    ChallengeChoose a checked column test
  14. 14
    TipUse quick plots while checking an input
  15. 15
    ChallengeRead several files into a preallocated list
  16. 16
    RecapTrace shape through each expression

Joins in R practice questions

50 Practice Questions in 5 sets

Set 1: Keys, matches and reusable calculations10 Practice Questions

Question 1 of 10

A sensor table has one row per sensor, while a measurement table repeats sensor IDs on different dates. What role does sensor ID have in the measurement table?
  1. A primary key identifying each measurement.
  2. A surrogate key assigned separately to each date.
  3. A foreign key referring to the sensor table.
  4. A compound key containing the date by itself.
Show answerHide answer
Answer: C
Sensor ID refers from each measurement to the sensor it belongs to, so it is a foreign key. It can repeat because one sensor can produce several measurements. A primary key would have to distinguish measurement rows, which sensor ID alone cannot do here.

Question 2 of 10

A lab must retain every sample row while adding details from a lookup with one row per device. Some samples have unknown device IDs. What join keeps the required sample rows?
  1. A left join from samples to devices.
  2. An inner join from samples to devices.
  3. A right join from samples to devices.
  4. A semi join from samples to devices.
Show answerHide answer
Answer: A
A left join keeps every sample and fills added device fields with NA when no partner exists. The unique device lookup prevents repeated matches from increasing the row count. An inner join would discard samples whose device IDs are absent from the lookup.

Question 3 of 10

A table has one row per plot per date, and a lookup has rainfall for several dates at each plot. Why can joining on plot alone attach the wrong rainfall?
  1. Matching plot automatically chooses the newest date.
  2. Different dates force all rainfall values to be missing.
  3. The join drops dates that occur more than once.
  4. Dates from the same plot all qualify as matches.
Show answerHide answer
Answer: D
The plot condition accepts every rainfall row with the same plot, regardless of date. Include both plot and date so the rainfall belongs to that observation. The join does not infer a most recent or same-day rule merely because date columns exist in both inputs.

Question 4 of 10

A table lists all training courses. A second table lists registrations, with several registrations per course. How can you retain courses with registrations without adding registration columns?
  1. Inner join courses to registrations.
  2. Semi join courses to registrations.
  3. Anti join courses to registrations.
  4. Full join courses to registrations.
Show answerHide answer
Answer: B
A semi join keeps a course if at least one registration matches and leaves the course columns unchanged. Extra registrations do not multiply that course row. An inner join would add registration information and repeat courses with several registrations.

Question 5 of 10

A left table has flow values 8, 18 and 31 L/min. A right lookup has lower thresholds 10, 20 and 20 L/min. A default left join uses flow >= lower. How many output rows result?
  1. 4 rows.
  2. 5 rows.
  3. 6 rows.
  4. 3 rows.
Show answerHide answer
Answer: B
The 8 L/min observation has no eligible threshold but survives once because this is a left join. The 18 L/min observation matches threshold 10 once; the 31 L/min observation matches all three lookup rows, giving five output rows in total. Counting distinct threshold values would miss the two separate rows at 20.

Question 6 of 10

What does this call return?

shift <- function(x, amount = 2) x + amount
shift(c(3, 8))
  1. A vector containing 3 and 8.
  2. A single value equal to 13.
  3. A vector containing 6 and 16.
  4. A vector containing 5 and 10.
Show answerHide answer
Answer: D
The omitted amount uses its default value of 2, which is added to both elements of x. The last expression returns the vector 5, 10. A function does not summarize its input unless its body contains a calculation that reduces the values.

Question 7 of 10

What happens when f <- function(x) if (x > 0) "yes" else "no" is called with c(2, -3)?
  1. It returns "yes" after checking the first value.
  2. It returns two labels, "yes" and "no".
  3. It errors because the condition has length two.
  4. It returns "no" after checking the final value.
Show answerHide answer
Answer: C
The comparison produces two logical values, but if needs one condition for the whole branch. It therefore errors instead of labeling each input. if_else() is the vectorized tool that can return a separate label for each element.

Question 8 of 10

A tibble has a = c(2, NA, 6) and b = c(5, 7, NA). What values result from summarize(across(a:b, \(x) mean(x, na.rm = TRUE)))?
  1. a = 4 and b = 6.
  2. a = NA and b = NA.
  3. a = 8 and b = 12.
  4. a = 3 and b = 4.
Show answerHide answer
Answer: A
The anonymous function removes missing values separately in each column. The mean of 2 and 6 is 4; the mean of 5 and 7 is 6. Missing results would occur with the default mean calculation, but the supplied na.rm = TRUE changes that behavior.

Question 9 of 10

Each input item produces a complete data frame. What does map(items, build_table) return?
  1. A single data frame with every result stacked.
  2. A numeric vector containing each row count.
  3. A matrix with one output column per item.
  4. A list containing one data frame per item.
Show answerHide answer
Answer: D
map() stores each call's result as one element of a list, so each data frame remains a separate element. It does not combine those frames automatically. Use a subsequent list_rbind() when the intended result is one table stacked by rows.

Question 10 of 10

For x <- c(4, NA, 11), what does x[x > 7] return?
  1. 11 alone.
  2. NA followed by 11.
  3. 4 followed by 11.
  4. An empty numeric vector.
Show answerHide answer
Answer: B
The comparison is FALSE, NA, TRUE, so logical indexing produces an unknown value followed by 11. A missing condition creates missing output. Returning only 11 would require dropping unknown conditions, for example with x[which(x > 7)].
Set 2: Choose tools and trace their results10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A proposed key check records |> count(code) |> filter(n > 1) returns zero rows. One record has a missing code. What further check is needed before using code as a primary key?
  1. Number the rows of each table separately.
  2. Inspect and resolve missing key values.
  3. Accept the key since no code repeats.
  4. Convert codes to numbers and recount.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Left keys are c("A", "A", "B", "D"); a unique right lookup has keys c("A", "B", "C"). How many rows result from the inner and full joins, respectively?
  1. 2 and 4.
  2. 4 and 4.
  3. 3 and 4.
  4. 3 and 5.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

An expected grid contains devices P and Q on days 1, 2 and 3. Observed pairs are P1, P3 and Q2. What remains after anti joining observations from the expected grid on device and day?
  1. P2, Q1 and Q3.
  2. P1, P3 and Q2.
  3. P2 and Q2 only.
  4. P1, P2 and P3.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

For one machine, calibrations occur on April 4 and April 11 with offsets 0.3 and -0.2. Readings occur April 2, April 11 and April 15. A left join uses closest(read_date > cal_date). What offsets result, in reading order?
  1. NA, -0.2, -0.2.
  2. 0.3, 0.3, -0.2.
  3. NA, 0.3, -0.2.
  4. NA, NA, -0.2.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A wrapper uses group_by(group_col) and fails because no column named group_col exists. The caller passed the bare column name region. What expression should replace the grouping argument?
  1. "group_col"
  2. {{ region }}
  3. {{ group_col }}
  4. group_col == region
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A rescaling function computes (x - min(x)) / (max(x) - min(x)). What happens for c(9, 9, 9)?
  1. It returns NaN for all three elements.
  2. It returns 0 for all three elements.
  3. It returns 1 for all three elements.
  4. It returns NA only for the middle element.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A script runs from a project folder and reads CSV files from its inputs subfolder. What list.files() option makes the returned paths include inputs/?
  1. recursive = FALSE
  2. all.files = TRUE
  3. ignore.case = TRUE
  4. full.names = TRUE
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A table has numeric columns u and v. What output name is made for the mean of u by across(u:v, list(avg = mean), .names = "{.fn}_{.col}")?
  1. u_avg
  2. avg_u
  3. mean_u
  4. avg_v
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

With column <- "rain_mm", how do you extract that named column from df using the variable?
  1. df[[column]]
  2. df$column
  3. df["column"]
  4. df[["column"]]
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A function preallocates an output vector, then loops over 1:length(x). It works for ordinary input but misbehaves when x is empty. Why, and what sequence fixes it?
  1. The sequence becomes 0 only; use seq_along(x).
  2. The sequence becomes 1 only; use length(x).
  3. The sequence stays empty; use seq_len(1).
  4. The sequence becomes 1, 0; use seq_along(x).
Show answerHide answer

Save this lesson to see this answer.

Set 3: Debug joins, functions and containers10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Left keys are c(1, 2, 2, 4) and right keys are c(1, 2, 2, 2, 3). A default left join is summed later. How many rows appear, and what does relationship = "many-to-one" do?
  1. 7 rows; the relationship check errors.
  2. 8 rows; the relationship check keeps the first match.
  3. 8 rows; the relationship check errors.
  4. 6 rows; the relationship check drops key 4.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A reading table has columns id and name, where name is a sensor label. A staff table has id, name and email, where name is a person. IDs correctly link sensors to staff. Why does omitting by lose expected email matches?
  1. The natural join also requires the two name values to match.
  2. The natural join ignores IDs and matches only the first column.
  3. A shared name column always prevents a left join from running.
  4. The natural join pairs rows only when their positions match.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A job spans hours 5–9. Shift A spans 0–6 and shift B spans 6–10. With default inclusive endpoints, which shifts match the job under overlaps() and under within()?
  1. Overlap: B only; within: B only.
  2. Overlap: A and B; within: B only.
  3. Overlap: neither; within: neither.
  4. Overlap: A and B; within: neither.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A function is defined globally as adjust <- function(x) x + offset. With offset <- 4, it returns 7 for input 3. After offset <- 9, what does adjust(3) return, and why?
  1. 7, because the original offset was copied into the body.
  2. 12, because the global offset is looked up when used.
  3. 3, because functions cannot read global variables.
  4. An error, because changing a global deletes the function.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A wrapper must accept a selection such as c(region, device) for grouping and a bare measurement column for averaging. How should those arguments be used inside it?
  1. group_by({{ groups }}) and mean("value").
  2. group_by(pick({{ groups }})) and mean({{ value }}).
  3. group_by(pick(groups)) and mean({{ value }}).
  4. group_by("groups") and mean(pick(value)).
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Each list element is a numeric vector. Why does map_dbl(groups, range) fail for nonempty vectors with ordinary finite values?
  1. Each range returns integers, but doubles cannot store integers.
  2. The mapper visits all vector elements together in one call.
  3. Each range returns two values, but each output slot needs one.
  4. The mapper requires all input vectors to have equal lengths.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Two CSVs describe the same measurement as value_c and temperature_c. Each is read successfully, then the tables are passed to list_rbind(). What problem appears, and where should it be fixed?
  1. Two partly missing columns; rename within the single-file reader.
  2. One correctly merged column; no cleaning step is needed.
  3. No rows from the second file; change to list_cbind().
  4. A random choice of column; sort paths before reading.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

With x <- c(6, 8, 9), a script uses x[-which(x > 20)] to remove large values. What does it return, and what expression retains the intended data?
  1. All three values; use x[x <= 20].
  2. An empty vector; use x[which(x > 20)].
  3. All three values; use x[-1].
  4. An empty vector; use x[x <= 20].
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

For parts <- list(a = c(2, 5), b = "ok"), what is the difference between parts["a"] and parts[["a"]]?
  1. The first is a numeric vector; the second is a list.
  2. Both are lists, but only the first retains the name.
  3. The first is a list; the second is a numeric vector.
  4. Both are numeric vectors, but only the first is sorted.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An analysis function needs one logical result per table column and should fail if a callback returns two values. Which call expresses that requirement?
  1. sapply(df, check_column)
  2. vapply(df, check_column, logical(1))
  3. lapply(df, check_column)
  4. tapply(df, check_column, length)
Show answerHide answer

Save this lesson to see this answer.

Set 4: Combine checks across an analysis10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Two teams independently add IDs 1, 2 and 3 to their own tables, then join those IDs. Each ID column is complete and unique, but the observations are in different orders. What does the key check fail to establish?
  1. That each current ID occurs only once per table.
  2. That the joined rows can have any missing cells.
  3. That the row numbers contain compatible numeric values.
  4. That equal IDs refer to the same real observations.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A unique device lookup contains D1, D2 and D3; the event table contains D1, D1 and D4. A left join runs from events to devices with unmatched = "error". Which keys make it fail?
  1. D2 and D3.
  2. D4 only.
  3. D1 and D4.
  4. D2, D3 and D4.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A permissions table allows pairs (user U, project X) and (user V, project Y). A request has (user U, project Y). Why can separate %in% checks wrongly accept it?
  1. Each value must occur exactly twice before it is allowed.
  2. A compound-key semi join would also accept every such pair.
  3. Each value exists somewhere, but the requested pair does not.
  4. The order of the permissions rows changes which pairs exist.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A rolling left join labels readings using closest(value >= lower). A lookup has lower values 0, 15, 15 and 40. A reading is 18, and exactly one label is required. What problem remains, and what check catches it?
  1. Only the 40 row matches; use relationship = "one-to-many".
  2. Both 15 rows match; use relationship = "many-to-one".
  3. No lower value matches; use unmatched = "error".
  4. All four rows match; use multiple = "all".
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A summary function accepts na.rm = TRUE but calls sd(x, na.rm = na.rm) / mean(x). For c(3, 6, NA, 9), why is the result still missing?
  1. The mean still uses its default missing-value behavior.
  2. The standard deviation always returns missing for four inputs.
  3. Defaults cannot be passed from one function to another.
  4. Division discards the explicit na.rm argument on both sides.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A wrapper computes the mean of a supplied bare column var and should name its output avg_ followed by that column name. What naming expression belongs in summarize()?
  1. "avg_var" = mean({{ var }})
  2. avg_var := mean("var")
  3. "avg_{{ var }}" := mean({{ var }})
  4. "avg_{{ var }}" = mean(var)
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A group contains three missing values in column a and observed values in column b. A grouped summary computes means with na.rm = TRUE. What should you expect for that group's a mean, and why?
  1. 0, because removing missing values replaces them with zero.
  2. The mean of b, because across() pools selected columns.
  3. No group row, because an empty mean drops the group.
  4. NaN, because no values remain for its mean.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

For map2_dbl(c(2, 4), c(5, 9), \(a, b) a + b), what values are returned?
  1. 7, 11, 9 and 13.
  2. 7 and 13.
  3. 10 and 36.
  4. 6 and 14.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Three input files should contain 2, 4 and 3 rows. A reader wrapped with possibly(..., otherwise = NULL) returns tables of 2 and 3 rows for the first and third files, and NULL for the second. After list_rbind(), what row count and completeness decision are justified?
  1. 9 rows; the second file is represented by four automatically inserted rows.
  2. 5 rows; investigate the missing second file before reporting the whole folder.
  3. 5 rows; the folder is complete because every retained row came from a valid file.
  4. 6 rows; NULL contributes one missing row that represents the second file.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A process starts at 80 and adds 25% of its current value on each of two steps. A mapper independently computes 80 * 1.25 twice. Why is that not the required process?
  1. The second step must use 100, producing 125.
  2. The second step must reuse 80, producing 100.
  3. Both steps must add 25 units, producing 130.
  4. Both steps must multiply the two results, producing 10000.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Audit a pipeline and repair near misses10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A left join from 12 events to a lookup returns 12 rows with relationship = "many-to-one". Some added labels are NA. What still needs checking to decide whether all event IDs have partners?
  1. Assume all IDs matched because row count stayed unchanged.
  2. Set unmatched = "error" on the left join to check event gaps.
  3. Run an anti join from events to the lookup on the same keys.
  4. Set multiple = "first" so missing labels select another row.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Left IDs are c("09", NA, "11"); right IDs are c("09", NA, NA). How many rows do default left joins return with na_matches = "na" and with na_matches = "never", respectively?
  1. 3 rows and 3 rows.
  2. 4 rows and 2 rows.
  3. 3 rows and 4 rows.
  4. 4 rows and 3 rows.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

An expected grid has four tanks on four dates. Its anti join to observations on tank and date returns five rows. One present tank-date has three observation rows. How many expected pairs are represented, and does the repeated observation alter that count?
  1. 11 pairs; repeated matches do not change it.
  2. 8 pairs; repeated matches remove three pairs.
  3. 16 pairs; repeated matches fill the missing pairs.
  4. 13 pairs; repeated matches add two more pairs.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A service interval spans hours 4–7. Windows A and B span 1–4 and 7–10. With default overlaps() bounds, what matches occur, and why might this surprise someone thinking only of shared duration?
  1. Neither matches because no positive duration is shared.
  2. Both windows match because endpoint contact counts.
  3. Only A matches because starts count but ends do not.
  4. Only B matches because ends count but starts do not.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A ratio wrapper checks is.numeric(b) and then uses if (b == 0) return(NA_real_). It receives b = c(0, 2). What additional input requirement addresses this failure without changing it into a vector function?
  1. Require at least two denominator values.
  2. Convert the logical test to character.
  3. Require one non-missing denominator.
  4. Replace zero denominators with the mean.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

You must keep original columns p and q while adding versions where missing entries become zero. What use of across() expresses that?
  1. mutate(across(p:q, \(x) coalesce(x, 0), .names = "{.col}"))
  2. summarize(across(p:q, \(x) mean(x, na.rm = TRUE), .names = "{.col}_filled"))
  3. filter(if_all(p:q, \(x) !is.na(x)))
  4. mutate(across(p:q, \(x) coalesce(x, 0), .names = "{.col}_filled"))
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A named list has two tables with 2 and 3 rows. You map a cleaning function that keeps those row counts, then use list_rbind(names_to = "source"). What should the result contain?
  1. Three rows with each row labeled by the column names.
  2. Five rows with each row labeled by its input list name.
  3. Two list elements with source stored outside the tables.
  4. Six rows formed by every pair of rows across the inputs.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A file path stored in path ends in "survey-2028.csv". What does parse_number(basename(path)) return, and how should the positive integer year be extracted?
  1. -2028; extract the four year digits, then convert them with as.integer().
  2. 2028; keep the parsed number because the hyphen only separates name parts.
  3. NA; remove only the ".csv" suffix, then convert the remaining name with as.numeric().
  4. 2028; convert the complete file name with as.integer() to preserve its year.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A base data.frame named d has id = 1:3 and mass_kg = c(4, NA, 9). A function needs a one-column data frame containing only masses above 6 kg. What selection meets both requirements?
  1. d[d$mass_kg > 6, "mass_kg", drop = FALSE]
  2. d[which(d$mass_kg > 6), "mass_kg"]
  3. d[which(d$mass_kg > 6), "mass_kg", drop = FALSE]
  4. d[, "mass_kg", drop = FALSE]
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A base data frame d has a column temperature_c. Why is d[["temperature_c"]] safer than d$tem when scripts may later gain other columns?
  1. It allows several matching name prefixes instead of requiring just one.
  2. It requires the exact stored name instead of a unique prefix.
  3. It creates a missing column if the exact name is absent.
  4. It returns a table instead of a numeric column vector.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

75 Key Terms, each with its definition

A

All-column predicate
An all-column predicate is true for a row when every selected column passes a test, as produced by if_all().
Using if_all(a:b, \(x) !is.na(x)) keeps only rows with both selected measurements present.
Anonymous function
An anonymous function is defined without a stored name, often directly where another function needs a small calculation.
The expression \(x) mean(x, na.rm = TRUE) supplies one calculation to a columnwise operation.
Anti join
An anti join keeps left-hand rows that have no matching right-hand partner and preserves the columns of the left input.
An anti join from readings to stations lists readings whose station identifiers are absent from the lookup.
Any-column predicate
An any-column predicate is true for a row when at least one selected column passes a test, as produced by if_any().
Filtering with if_any(a:b, is.na) keeps a row if a or b contains a missing measurement.
Apply family
The apply family provides base R functions for repeated or grouped calculations, with different rules for result containers.
lapply() keeps a list, while tapply() can compute a mean for each group in a separate grouping vector.

C

Character index
A character index selects named vector elements or table columns by matching supplied strings to their stored names.
Requesting c("c", "a") from a named vector selects element c first and then element a.
Column binding
Column binding places tables side by side, combining their columns rather than matching observations through join keys.
list_cbind() can place compatible result columns alongside each other when their row alignment is already known.
Column selector
A column selector identifies which columns an operation should use through names, positions, ranges or selection helpers.
The selector where(is.numeric) chooses numeric columns while leaving text columns out of the calculation.
Columnwise operation
A columnwise operation applies the same function independently to selected columns, such as through across() in dplyr.
Temperature and rainfall can each receive a missing-value count without writing two separate calculations.
Compound key
A compound key uses several columns together to identify a row when none of those columns identifies it on its own.
A station and date together identify one daily reading, even though stations and dates each repeat.
Cross join
A cross join pairs every row of one table with every row of another, producing the product of their row counts.
Crossing three stations with two dates creates six station-days to check against recorded observations.

D

Data masking
Data masking lets a calculation refer directly to data columns as names, as in mean(temp_c) inside summarize().
A filtering expression compares a temperature column to a threshold without writing the table name each time.
Default argument value
A default argument value supplies an argument when the caller omits it, while allowing a different value in an explicit call.
A summary may default to na.rm = FALSE but let a caller request removal of missing values.
Dimension dropping
Dimension dropping simplifies a selection to a lower-dimensional object, such as one base data frame column becoming a vector.
Adding drop = FALSE keeps a one-column data frame when later code still expects table operations.

E

Early return
An early return finishes a function call before the remaining body runs, often handling a special case near the start.
A scalar ratio returns NA_real_ for a zero denominator before reaching the ordinary division step.
Edge case
An edge case is an unusual but relevant input that can expose a function's limits, such as empty, constant or infinite values.
A constant input makes a standard range-based rescaling divide by zero, producing NaN values.
Element extraction
Element extraction retrieves one stored list element itself with [[ or $, instead of returning a list that contains it.
Extracting results[[1]] gives the table from the first mapping call, ready for ordinary table operations.
Embracing
Embracing surrounds an argument with {{ }} to forward a caller-supplied column expression into a tidyverse operation.
Using mean({{ var }}) lets a wrapper calculate the mean of the bare column supplied by its caller.
Equality join
An equality join matches rows when the specified key values are equal, possibly requiring equality on several columns together.
A rainfall value matches a reading only when both its station identifier and its observation date agree.
Error fallback
An error fallback is a replacement result returned when a wrapped function errors, such as NULL supplied by possibly().
A failed import becomes NULL; inspect its named path before row binding skips it and combines the good files.

F

File path
A file path identifies a file's location, including the folder information a reader needs relative to its working directory.
A listed path such as "data/readings-2024.csv" retains the data folder when read from the project root.
Foreign key
A foreign key is a column or combination of columns whose values refer to the primary key of another table.
Each daily reading carries a station ID so it can be linked to that station's location and elevation.
Full join
A full join retains matched pairs and unmatched rows from both inputs, filling unavailable fields with missing values.
Both an unrecognized reading and a station with no readings remain visible after a full join.
Function argument
A function argument is an input named in a function's interface that lets the caller supply data or change an option.
In a rescaling function, the argument x receives the values to rescale, while na.rm controls how missing data are handled.
Function body
A function body contains the expressions evaluated when the function is called, using supplied arguments and local values.
A rescaling body finds a range, subtracts its minimum and divides the shifted values by its width.

I

Implicit missing value
An implicit missing value is an expected observation with no row in the data, so there is no cell containing an explicit NA.
An expected station-date grid reveals a day with no reading by anti joining the recorded pairs.
Indirection
Indirection occurs when a function receives a column expression through an argument instead of referring to the column directly.
A grouped-mean wrapper receives site through group_var, then must forward that expression to dplyr.
Inequality join
An inequality join returns row pairs that meet comparisons such as greater than or equal to, instead of requiring equal values.
A speed above several lower thresholds matches every one of those thresholds in a plain inequality join.
Inner join
An inner join returns matched row pairs and excludes observations in either input that have no matching partner.
A reading for an absent station disappears when readings are inner joined to the station lookup.
Input validation
Input validation checks whether arguments meet the requirements of a calculation before the function tries to use them.
A scalar ratio checks that its denominator is numeric, has length one and is not missing before branching.

L

Left join
A left join retains every left-hand row and adds matching right-hand values, using missing values when there is no partner.
An unknown station ID stays in the reading table with NA in the added site and elevation columns.
Lexical scoping
Lexical scoping resolves nonlocal names through the environment where a function was defined, rather than the caller's local variables.
A function referring to a global offset can change results after that external offset is changed.
List
A list is a container whose elements can have different types and lengths, including vectors, data frames and other lists.
A mapped analysis can keep a numeric vector, a plot and a nested diagnostics object in separate list elements.
Logical index
A logical index retains positions marked TRUE, drops those marked FALSE and produces missing output for unknown positions.
For values 5, NA, 8, the condition x > 6 selects a missing result followed by the value 8.
Loop body
A loop body is the code executed for each value of a loop variable, usually reading the current input and storing its result.
Inside a square-root loop, out[i] <- sqrt(v[i]) reads and fills the matching position on each pass.
Loop sequence
A loop sequence supplies the successive values of a loop variable, with seq_along() generating valid positions for an input.
An empty input produces no positions with seq_along(), so a loop body does not run accidentally.

M

Many-to-many relationship
A many-to-many relationship occurs when matching key values connect several rows on each side of a join.
Two rows for one key on the left and three on the right produce six matched pairs for that key.
Mapping
Mapping applies a function independently to each input element and collects one output element per call, preserving input length.
Mapping a plotting function over station tables produces a list holding one plot object for each station.
Missing-key matching
Missing-key matching determines whether two missing key values count as equal partners; dplyr permits this by default.
Setting na_matches = "never" keeps two unknown station IDs from being treated as a shared identifier.
Multiple-match selection
Multiple-match selection chooses which partners to retain when a left row matches several right rows, using the multiple argument.
Setting multiple = "first" takes a partner in right-hand order; it does not choose the latest date.
Mutating join
A mutating join adds columns by matching rows across two tables, with the join type deciding which unmatched rows survive.
A reading can gain its station's site name and elevation without those details being stored in every input row.

N

Name injection
Name injection builds an output name from a supplied expression using :=, so a reusable calculation can label its result.
A mean wrapper creates mean_temp_c when its name template includes the supplied temperature column.
Natural join
A natural join chooses every shared column name as a matching key when no explicit join specification is supplied.
Two unrelated name columns can prevent valid ID matches if the join specification is omitted.
Negative index
A negative index names positions to omit from a selection and cannot be mixed with positive positions except for zero.
The expression x[-2] retains every vector element except the one in the second position.

O

One-to-many relationship
A one-to-many relationship lets one row in a first table have several matching rows in a second table.
A station has one details row but can have many reading rows, one for each observation date.
Orphan row
An orphan row has a foreign-key value with no corresponding primary-key value in the table it should refer to.
A reading labeled S4 is orphaned when the station table lists only S1, S2 and S3.
Output-name pattern
An output-name pattern controls generated column names, using placeholders such as {.col} and {.fn} in across().
The pattern "{.fn}_{.col}" names the average of column a as avg_a when the function is named avg.

P

Paired iteration
Paired iteration passes corresponding elements of several inputs together to each function call instead of creating all combinations.
map2() can pair each table with its own threshold, one position from each input at a time.
Partial matching
Partial matching accepts a unique beginning of a stored name, which base $ can do when looking up a column.
The abbreviation d$te can find temp_c, but adding another column with that prefix makes it unreliable.
Point-in-range match
A point-in-range match tests whether one value lies between a lookup interval's endpoints, including both endpoints by default.
The helper between(date, start, end) can label a reading with the season containing its date.
Positional index
A positional index selects vector elements by their numbered locations, starting at 1 and following the supplied index order.
The selection x[c(3, 1)] returns the third value before the first, regardless of their original order.
Preallocation
Preallocation creates an output container at its intended size before iteration, so results can fill existing positions.
A loop prepares vector("double", length(x)) before storing one computed value per input position.
Primary key
A primary key is a column or combination of columns that uniquely identifies each row in a table and has no missing key values.
In a table with one row per station, station_id identifies the station whose elevation is recorded.

R

Range containment
Range containment requires an entire left-hand interval to fit within a right-hand interval, as checked by the within() helper.
A job ending at hour 12 is not wholly within a shift ending at hour 10, even if it starts during that shift.
Range overlap
A range overlap occurs when two intervals share at least one point under the specified endpoint rules used by overlaps().
With default bounds, a job ending exactly when a shift starts counts as overlapping that shift.
Relationship check
A relationship check enforces expected maximum matches per row and stops a join when its data violate that expectation.
A many-to-one check catches two station lookup rows that would both match the same daily reading.
Result template
A result template states the required type and shape of each vapply() result, allowing incompatible callbacks to fail clearly.
The template logical(1) requires one logical value per call when checking whether table columns are numeric.
Return value
A return value is the result of a function call, taken from its last evaluated expression unless return() ends the call earlier.
A rescaling function returns a vector that can be assigned to a new column in a mutate() call.
Right join
A right join retains every right-hand row, adding left-hand matches and missing left-hand fields where no match exists.
A station with no readings still appears when the station lookup is the right input of a right join.
Rolling join
A rolling join selects the closest value that satisfies an inequality; tied rows at that value can still give several matches.
A reading can take the latest calibration on or before its date by using closest(date >= cal_date).
Row binding
Row binding stacks data frames vertically, aligning their columns by name and combining compatible types into one table.
list_rbind(names_to = "source") stacks a named list of cleaned tables and records each table's origin.
Row multiplication
Row multiplication occurs when one input row appears several times in a join result because it has several matching partners.
A total can become inflated when a reading is repeated after matching several lookup records.

S

Scalar condition
A scalar condition is one non-missing logical value that lets if select a single branch for the current function call.
Testing a whole numeric vector with x > 0 creates several conditions and cannot directly control one if.
Semi join
A semi join keeps left-hand rows that have at least one right-hand match without adding columns or multiplying those rows.
A course appears once in a course list even when several registrations show that it has participants.
Side effect
A side effect is an action a function performs beyond returning a value, such as printing a result or writing a file.
A file-saving task uses walk2() because writing each output matters more than collecting return values.
Single-file reader
A single-file reader is a function that imports and cleans one path, giving every file the same names and intended column types.
Test one file from each layout before mapping the reader over a folder and binding its returned tables.
Source column
A source column records the input file or list element that supplied each row of a combined data set.
The id = "file" argument keeps source paths beside readings imported from several CSV files.
Split-apply-combine
Split-apply-combine divides data into groups, runs a function on each part and collects or combines the resulting objects.
Splitting measurements by site supports one plot per site, stored as a list for later saving.
Structure inspection
Structure inspection uses a display such as str() to show an object's container, element types and levels of nesting.
Inspecting a JSON-derived list helps locate the inner numeric vector before extracting it with [[.
Surrogate key
A surrogate key is an artificial identifier assigned to a row, whose stored value can be referenced from other tables.
A station receives an assigned ID once, and later readings carry that same ID as their foreign key.

T

Tidy selection
Tidy selection chooses columns by names, positions or helpers, and has different rules from ordinary column calculations.
A wrapper can forward starts_with("temp") into select() or an across() column selection.
Type guessing
Type guessing infers a column's data type from sampled input values, which may give text output when numeric data contain text.
An unexpected "n/a" entry can change an intended numeric measurement column to character during import.
Typed mapper
A typed mapper collects one compatible scalar per input into a specified atomic vector, such as doubles with map_dbl().
A mean per numeric column can form a double vector, but a minimum-and-maximum pair needs list output.

U

Unmatched-row check
An unmatched-row check can stop a join when observations that would be dropped have no partner in the other input.
For a left join, unmatched = "error" checks unused lookup rows because left rows are retained.

V

Vectorized choice
A vectorized choice selects an output separately for each input position, as if_else() does for a logical vector.
Three temperatures can receive three labels in one call without choosing a single label for the whole vector.

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