Joins in R
Joins, Functions and Iteration in R
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
- 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 tablesRecognize 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 joinsUse 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 problemsPredict 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.
- Identify and check the keys that connect tables
- 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 joinsUse 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 rangesUse 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.
- Keep or drop rows with semi and anti joins
- 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 valuesDecide 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 readableUse 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 embracingExplain 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.
- Write vector functions with arguments and return values
- 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 purrrUse 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 outputsList 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.
- Apply functions to many columns with across()
- 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
[tofilter()andselect(). - Extract single elements with $ and [[ and work with listsPull 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 familyWrite 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.
- Select elements of vectors and data frames with [
Joins in R study guide
1Combine 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.
| Join | Rows retained | Result here |
|---|---|---|
left_join() | Every row of x | Four readings, including S4 |
inner_join() | Matched rows only | Three readings; S4 disappears |
right_join() | Every row of y | Three matched readings plus S3 |
full_join() | Every row of both tables | Four 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 = TRUEretains 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
| Argument | What it controls | Important detail |
|---|---|---|
relationship | Maximum matches per row | Does not require a match to exist |
unmatched | Unmatched rows that would be dropped | A left join checks y |
multiple | Which matches of a left row to return | Default "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
relationshipto 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.
2Filter 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.
3Write 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
ifrequires 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 oraes(). - 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 andenglue()for expression-based text.
4Repeat 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
.namescontrol output column names. if_any()andif_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.
| Function | Result |
|---|---|
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, andimap()supplies names or positions.- Use
walk()for side effects. - Bind table results with
list_rbind()orlist_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 withNULL; inspect failures before binding.- Use
walk2()to pair each output object with its destination path.
5Read 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.
| Selection | Base data.frame | Tibble |
|---|---|---|
df[, "temp_c"] | A vector | A one-column tibble |
df[, "temp_c", drop = FALSE] | A one-column data frame | A 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
TRUEpositions. - Repeated indices repeat values; character indices select named elements.
- Logical
NAindices create missing output;which()keeps onlyTRUEpositions. - Data frame indices are rows first, columns second;
drop = FALSEpreserves 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 invar. - Base
$can partially match names;[[matches exactly by default. - Assigning
NULLremoves 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:
| Function | Result 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
1Attach station details without losing readings
14 steps
- 1IntroductionPlan 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.
- 2ExplanationRead the two row meanings
In
stations,station_idis a primary key: it identifies one station row. Inreadings, 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_idanddateidentifies each daily reading, while station alone does not. The relationship is many-to-one from readings to stations. - 3ExampleTest 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.
- 4ChallengeIs 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.
- 5ExampleTrace 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.
- 6ConnectionChanging 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.
- 7TipMake keys and column origins explicit
If the lookup calls its key
id, writejoin_by(station_id == id). Equality joins normally keep the left key;keep = TRUElets you inspect both input keys.For station-day data, include the date as well. Shared non-key column names receive
.xand.ysuffixes. Unexpecteddate.xanddate.yare a reason to check whether date was omitted from a compound key. - 8ChallengeKeep 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.
- 9ExamplePredict 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.
- 10ExplanationEnforce 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.
- 11Key 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.
- 12ChallengeCatch 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.
- 13ChallengeAudit 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. - 14RecapUse 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.
2Find gaps and choose time-based matches
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionChoose what a match should answer
- 2ExampleSelect stations that reported
- 3ExplanationReverse the gap check carefully
- 4ChallengeKeep a requested pair together
- 5ExampleFind missing rows with an expected grid
- 6ExampleCount every eligible threshold
- 7ExampleChoose the closest eligible threshold
- 8TipCheck ties at the chosen value
- 9ConnectionUse the same rule for earlier dates
- 10ExplanationDistinguish overlap from containment
- 11ChallengeChoose a calibration at the boundary
- 12ChallengeCheck both reporting gaps and labels
- 13RecapTranslate the question into a match rule
3Build and test a reusable analysis function
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake one calculation reusable
- 2ExplanationSeparate inputs from the body
- 3ExampleWork through the returned vector
- 4TipForward options into each calculation
- 5ChallengeTest the zero-width case
- 6ExplanationKeep branching scalar
- 7ExampleValidate before handling a special case
- 8ConnectionMake an offset part of the interface
- 9ChallengeDiagnose a vector denominator
- 10ExplanationForward a column expression
- 11ExampleBuild a grouped-mean wrapper
- 12Key InsightSelection and calculation need different interpretation
- 13ExampleName the result from the supplied column
- 14ConnectionReturn a plot built from the same column
- 15ChallengeSeparate a column from an option
- 16ChallengeReview a function before mapping it
- 17RecapTest the interface as well as the formula
4Repeat one task across columns and files
19 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDecide what one call should receive
- 2ExampleCompute two means with one definition
- 3ExplanationName multiple calculations
- 4ChallengeKeep the row with both values present
- 5Key InsightGroups change the input to each mean
- 6ExampleChoose a container for each result
- 7ConnectionA table is a list of columns
- 8ExplanationPair inputs for each call
- 9ChallengeStore two values from every group
- 10ExampleBind returned tables and keep their names
- 11TipUse return values only when you need them
- 12ExampleList and read the folder
- 13ExampleUse one cleaning function for one path
- 14TipExtract a year before parsing it
- 15ChallengeA combined table has two temperature columns
- 16ExplanationKeep failures visible when continuing
- 17ExamplePair each saved table with a path
- 18ChallengeCheck a folder pipeline before reporting totals
- 19RecapChoose iteration from one call and its result
5Read a base R script without losing its structure
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFollow values and their containers
- 2ExampleSelect by position, exclusion or condition
- 3Key InsightAn unknown index leaves unknown output
- 4ExampleKeep a selected column as a table
- 5ChallengeRemove no values correctly
- 6ExplanationOpen one list element
- 7TipUse a stored name with double indexing
- 8ChallengeSelect a table stored inside a list
- 9ExampleAllocate, visit and store
- 10ExplanationMake empty input a normal case
- 11ConnectionRecognize independent and dependent steps
- 12ExplanationRead the output promise of an apply call
- 13ChallengeChoose a checked column test
- 14TipUse quick plots while checking an input
- 15ChallengeRead several files into a preallocated list
- 16RecapTrace shape through each expression
Joins in R practice questions
Set 1: Keys, matches and reusable calculations10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
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
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
flow >= lower. How many output rows result?Show answerHide answer
Question 6 of 10
What does this call return?
shift <- function(x, amount = 2) x + amount
shift(c(3, 8))
Show answerHide answer
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
f <- function(x) if (x > 0) "yes" else "no" is called with c(2, -3)?Show answerHide answer
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 = c(2, NA, 6) and b = c(5, 7, NA). What values result from summarize(across(a:b, \(x) mean(x, na.rm = TRUE)))?Show answerHide answer
na.rm = TRUE changes that behavior.Question 9 of 10
map(items, build_table) return?Show answerHide answer
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
x <- c(4, NA, 11), what does x[x > 7] return?Show answerHide answer
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
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?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
closest(read_date > cal_date). What offsets result, in reading order?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
(x - min(x)) / (max(x) - min(x)). What happens for c(9, 9, 9)?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
inputs subfolder. What list.files() option makes the returned paths include inputs/?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
u and v. What output name is made for the mean of u by across(u:v, list(avg = mean), .names = "{.fn}_{.col}")?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
column <- "rain_mm", how do you extract that named column from df using the variable?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
1:length(x). It works for ordinary input but misbehaves when x is empty. Why, and what sequence fixes it?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
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?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
overlaps() and under within()?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
adjust <- function(x) x + offset. With offset <- 4, it returns 7 for input 3. After offset <- 9, what does adjust(3) return, and why?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
c(region, device) for grouping and a bare measurement column for averaging. How should those arguments be used inside it?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
map_dbl(groups, range) fail for nonempty vectors with ordinary finite values?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
parts <- list(a = c(2, 5), b = "ok"), what is the difference between parts["a"] and parts[["a"]]?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
unmatched = "error". Which keys make it fail?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
%in% checks wrongly accept it?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
var and should name its output avg_ followed by that column name. What naming expression belongs in summarize()?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
map2_dbl(c(2, 4), c(5, 9), \(a, b) a + b), what values are returned?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
80 * 1.25 twice. Why is that not the required process?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
relationship = "many-to-one". Some added labels are NA. What still needs checking to decide whether all event IDs have partners?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
overlaps() bounds, what matches occur, and why might this surprise someone thinking only of shared duration?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
p and q while adding versions where missing entries become zero. What use of across() expresses that?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
list_rbind(names_to = "source"). What should the result contain?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
path ends in "survey-2028.csv". What does parse_number(basename(path)) return, and how should the positive integer year be extracted?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
d has a column temperature_c. Why is d[["temperature_c"]] safer than d$tem when scripts may later gain other columns?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
All-column predicate
if_all().if_all(a:b, \(x) !is.na(x)) keeps only rows with both selected measurements present.Anonymous function
\(x) mean(x, na.rm = TRUE) supplies one calculation to a columnwise operation.Anti join
Any-column predicate
if_any().if_any(a:b, is.na) keeps a row if a or b contains a missing measurement.Apply family
lapply() keeps a list, while tapply() can compute a mean for each group in a separate grouping vector.C
Character index
c("c", "a") from a named vector selects element c first and then element a.Column binding
list_cbind() can place compatible result columns alongside each other when their row alignment is already known.Column selector
where(is.numeric) chooses numeric columns while leaving text columns out of the calculation.Columnwise operation
across() in dplyr.Compound key
Cross join
D
Data masking
mean(temp_c) inside summarize().Default argument value
na.rm = FALSE but let a caller request removal of missing values.Dimension dropping
drop = FALSE keeps a one-column data frame when later code still expects table operations.E
Early return
NA_real_ for a zero denominator before reaching the ordinary division step.Edge case
NaN values.Element extraction
[[ or $, instead of returning a list that contains it.results[[1]] gives the table from the first mapping call, ready for ordinary table operations.Embracing
{{ }} to forward a caller-supplied column expression into a tidyverse operation.mean({{ var }}) lets a wrapper calculate the mean of the bare column supplied by its caller.Equality join
Error fallback
NULL supplied by possibly().NULL; inspect its named path before row binding skips it and combines the good files.F
File path
Foreign key
Full join
Function argument
x receives the values to rescale, while na.rm controls how missing data are handled.Function body
I
Implicit missing value
NA.Indirection
site through group_var, then must forward that expression to dplyr.Inequality join
Inner join
Input validation
L
Left join
NA in the added site and elevation columns.Lexical scoping
List
Logical index
TRUE, drops those marked FALSE and produces missing output for unknown positions.NA, 8, the condition x > 6 selects a missing result followed by the value 8.Loop body
out[i] <- sqrt(v[i]) reads and fills the matching position on each pass.Loop sequence
seq_along() generating valid positions for an input.seq_along(), so a loop body does not run accidentally.M
Many-to-many relationship
Mapping
Missing-key matching
na_matches = "never" keeps two unknown station IDs from being treated as a shared identifier.Multiple-match selection
multiple argument.multiple = "first" takes a partner in right-hand order; it does not choose the latest date.Mutating join
N
Name injection
:=, so a reusable calculation can label its result.mean_temp_c when its name template includes the supplied temperature column.Natural join
name columns can prevent valid ID matches if the join specification is omitted.Negative index
x[-2] retains every vector element except the one in the second position.O
One-to-many relationship
Orphan row
Output-name pattern
{.col} and {.fn} in across()."{.fn}_{.col}" names the average of column a as avg_a when the function is named avg.P
Paired iteration
map2() can pair each table with its own threshold, one position from each input at a time.Partial matching
$ can do when looking up a column.d$te can find temp_c, but adding another column with that prefix makes it unreliable.Point-in-range match
between(date, start, end) can label a reading with the season containing its date.Positional index
x[c(3, 1)] returns the third value before the first, regardless of their original order.Preallocation
vector("double", length(x)) before storing one computed value per input position.Primary key
station_id identifies the station whose elevation is recorded.R
Range containment
within() helper.Range overlap
overlaps().Relationship check
Result template
vapply() result, allowing incompatible callbacks to fail clearly.logical(1) requires one logical value per call when checking whether table columns are numeric.Return value
return() ends the call earlier.mutate() call.Right join
Rolling join
closest(date >= cal_date).Row binding
list_rbind(names_to = "source") stacks a named list of cleaned tables and records each table's origin.Row multiplication
S
Scalar condition
if select a single branch for the current function call.x > 0 creates several conditions and cannot directly control one if.Semi join
Side effect
walk2() because writing each output matters more than collecting return values.Single-file reader
Source column
id = "file" argument keeps source paths beside readings imported from several CSV files.Split-apply-combine
Structure inspection
str() to show an object's container, element types and levels of nesting.[[.Surrogate key
T
Tidy selection
starts_with("temp") into select() or an across() column selection.Type guessing
Typed mapper
map_dbl().U
Unmatched-row check
unmatched = "error" checks unused lookup rows because left rows are retained.V
Vectorized choice
if_else() does for a logical vector.About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.