- Learn
- Computer Science & IT
- Data Science & AI
- Data Analysis with R
- Tidy Data and Data Import in R
Tidy Data and Data Import in R
IntermediateLesson 4 of 7 in Data Analysis with R Course
What you will learn
- Recognize whether a dataset is tidy, and reshape untidy tables with tidyr's
pivot_longer()andpivot_wider()so that every variable is a column and every observation is a row.- Recognize tidy data and spot untidy layoutsState the three rules of tidy data, identify the variables and observations in a table, and diagnose which kind of reshaping an untidy table needs.
- Turn columns into rows with pivot_longer()Lengthen a table whose column names are values, choose the columns to pivot, name the new columns, drop or keep missing values, and give the new columns the right types.
- Split column names that hold several variablesLengthen tables whose column names combine two or more variables, using a separator or a pattern, and keep different measurements in their own columns with the
".value"name. - Turn rows into columns with pivot_wider()Widen a table in which one observation is spread over several rows, control which columns identify a row, and handle missing combinations and duplicate values correctly.
- Recognize tidy data and spot untidy layouts
- Read delimited text files into R with readr, control how columns are named and typed, handle regional formats such as semicolon files with decimal commas, combine many files, and save results in a format that suits the next step.
- Read a CSV file and check what you importedRead a comma-separated file with
read_csv(), tell readr how missing values, extra lines and headers are written, give the columns usable names and check the result. - Set column types and fix parsing problemsExplain how readr guesses column types, specify the types yourself, find the values that failed to parse and convert awkward text into numbers.
- Read semicolon, tab and other regional file formatsChoose the right readr function for the delimiter in a file, read numbers written with a decimal comma, set the text encoding and write files for users with other regional settings.
- Combine many files and save your dataRead a folder of files with the same columns into one table that records each row's source, type small tables directly in code, and choose between CSV, RDS and Parquet for saving data.
- Read a CSV file and check what you imported
- Read data from Excel workbooks and Google Sheets into R with readxl and googlesheets4, choosing the right sheet and cell range, handling the habits of spreadsheet users, and write results back to spreadsheet files.
- Read and write Excel workbooks with readxl and writexlList and read the sheets of an Excel workbook, select the cells that hold the data, set names, missing-value codes and types, combine sheets, and save data frames as an Excel file.
- Read and write Google Sheets with googlesheets4Read public and private Google Sheets into R, select sheets, ranges and column types, write data back, and keep analyses reproducible when the sheet keeps changing.
- Read and write Excel workbooks with readxl and writexl
- Connect to a database with DBI, run SQL queries, use dplyr verbs on database tables through dbplyr so that the database does the work, and read the SQL that dbplyr generates.
- Connect to a database and run SQL with DBIExplain what a database is and the main kinds of database systems, connect to one from R through DBI and a backend package, list, write and read tables, send SQL queries and close the connection.
- Use dplyr on database tables with dbplyrCreate a lazy reference to a database table, build queries with dplyr verbs, and bring the result into R at the right moment with
collect(). - Read the SQL that dbplyr writesRead basic SQL queries, map each dplyr verb to the SQL clause it produces, and know where SQL behaves differently from R, especially with missing values.
- Connect to a database and run SQL with DBI
- Store large data as partitioned Parquet files with the arrow package and analyze datasets that are larger than memory with dplyr, reading only the files and columns a question needs.
- Store data as partitioned Parquet filesExplain why large CSV files are slow, what the Parquet format and Apache Arrow are, and how to convert a large CSV file into a well-partitioned Parquet dataset.
- Query Arrow datasets with dplyrOpen a Parquet dataset, write dplyr pipelines that Arrow runs lazily, collect only the result, and pass a dataset to DuckDB when Arrow does not support an operation.
- Store data as partitioned Parquet files
Tidy Data and Data Import in R study guide
1Organize data in tidy form with tidyr
Analysis starts with a decision about what each row represents. Rainfall by station and year needs a different layout from a station lookup table. Learn to recognize variables hidden in headings, move them into columns, and bring separate measurements side by side. The pivot arguments make these choices explicit, including which identifiers stay fixed, how name pieces are split, and what missing combinations mean.
1.1 Find the observation before reshaping
A table can be easy to read and still be awkward to analyze. Before changing its shape, decide what one row should describe. In annual rainfall records, that unit is one station in one year. A station measured in three years contributes three observations.
Variables, observations, and values
A variable is a property you record, such as station, year, or rainfall in millimeters. An observation collects the values for one unit at one time. A value is one entry, such as 790 mm. Tidy data follows three rules together:
- Each variable occupies one column, and each column describes one variable.
- Each observation occupies one row, and each row describes one observation.
- Each value occupies one cell, and each cell contains one value.
These rules give column operations a stable meaning. With columns cases and population, mutate(rate = cases / population) calculates one rate for each observation. With year and rainfall_mm, ggplot2::aes(x = year, y = rainfall_mm) names the two variables directly.
Read the layout
Consider these rainfall records:
| station | year | rainfall_mm |
|---|---|---|
| Alpha | 2022 | 812 |
| Alpha | 2024 | 790 |
| Beta | 2022 | 640 |
| Beta | 2023 | 655 |
| Beta | 2024 | 701 |
Each row describes a station-year, so the layout is tidy. Now imagine columns named station, 2022, 2023, and 2024. The numbers in the headings are values of a missing year variable. pivot_longer() brings those headings into a year column and their measurements into a rainfall column.
Other symptoms point to different changes. A heading such as bike_am contains both a travel mode and a period; split its pieces while lengthening. A table with patient, test, and value may spread one patient observation across rows for different tests; pivot_wider() gives the tests their own columns. A cell containing "790/112" combines rainfall and rainy days; separate_wider_delim() can split those into separate variables.
Choose a shape for the meaning
More rows do not always mean better data. height_cm and weight_kg are distinct measurements with different units. They belong in separate columns when a row describes one person. Stacking both into an unexplained value column hides what the numbers measure.
Also separate tables that describe different units. Station coordinates and elevation describe a station, while rainfall describes a station-year. Store station details once in a table with one row per station. The shared station column links it to the rainfall records for a later join.
Tidy layout and accurate data are separate questions. A table can follow all three rules and still contain a mistyped measurement or a duplicate record. Reshaping gives variables and observations consistent places; cleaning checks the entries themselves.
Key Takeaways
- Define the unit represented by one observation.
- Keep each variable in a column, each observation in a row, and each value in a cell.
- Choose a pivot from the information hidden in headings or spread across rows.
- Store information about different observational units in separate linked tables.
1.2 Move headings into a column
Use pivot_longer() when a set of column names contains values of one variable. Keep the columns that identify each observation, and move the selected headings and measurements into two new columns.
Build and lengthen a small table
library(tidyverse)
rain_wide <- tibble(
station = c("Alpha", "Beta"),
`2022` = c(812, 640),
`2023` = c(NA, 655),
`2024` = c(790, 701)
)
rain_long <- rain_wide |>
pivot_longer(
cols = `2022`:`2024`,
names_to = "year",
values_to = "rainfall_mm",
names_transform = list(year = as.integer)
)
cols names existing columns. The backticks let R treat numeric headings as column names. names_to and values_to are quoted strings because they supply names for new columns. Without these arguments, the new columns are called name and value.
The output has six rows and three columns. Alpha contributes (2022, 812), (2023, NA), and (2024, 790); Beta contributes (2022, 640), (2023, 655), and (2024, 701). The station value repeats on each of its three rows. Predicting this size helps detect an incorrect selection: two original rows multiplied by three measurement columns gives six rows. The same reasoning gives 24,092 rows for 317 songs with 76 weekly rank columns before missing ranks are removed.
Select only the columns that belong together
Selection helpers work as they do in select(). cols = !station selects every column except station; starts_with("wk") selects week columns. An identifier accidentally included in cols becomes data to stack. It may also cause an error because text station names cannot be combined with numeric measurements. Height and weight should stay separate variables even though both are numeric.
Give the names their intended type
Old headings arrive as text by default. names_transform = list(year = as.integer) converts the new year column during the pivot. You can instead use mutate(year = as.integer(year)) afterward. For headings such as wk1, remove the prefix with names_prefix = "wk" before conversion, or use readr::parse_number() afterward. Text sorts "10" before "2"; numeric values sort in numeric order and support a numeric plot axis.
Decide what missing rows mean
Add values_drop_na = TRUE to remove rows with missing measurements. Here that leaves five rows. Keep the missing Alpha observation if you need to study measurement coverage. Dropping missing weekly chart ranks makes sense when a song had already left the chart.
With the missing row kept, calculate available-year means explicitly:
rain_long |>
group_by(station) |>
summarize(mean_mm = mean(rainfall_mm, na.rm = TRUE))
Alpha's mean is 801 mm; Beta's is about 665.3 mm. Without na.rm = TRUE, Alpha's missing value makes its mean NA. For a time plot, ggplot(rain_long, aes(year, rainfall_mm, color = station)) + geom_line() now refers to the variables by name.
Key Takeaways
- Use
colsfor existing measurement columns and quoted strings for new names. - Unpivoted identifiers repeat on the new rows.
- Convert numeric headings to a numeric names column when needed.
- Keep missing rows when their absence is part of the question.
- Predict the row count before dropping missing values.
1.3 Unpack names while keeping measurements separate
Some headings carry two pieces of information. bike_am names a travel mode and a period. Other headings, such as height_1, name a measurement and a week. The right pivot preserves these different meanings.
Split at a separator
library(tidyverse)
traffic <- tribble(
~city, ~bike_am, ~bike_pm, ~car_am, ~car_pm,
"Lund", 410, 380, 1250, 1310,
"Porto", 220, 260, 1890, 2040
)
traffic |>
pivot_longer(
cols = !city,
names_to = c("mode", "period"),
names_sep = "_", values_to = "count"
)
Each selected heading splits into two pieces in the order given by names_to. The output has eight rows: two cities, each contributing four mode-period counts. Its columns are city, mode, period, and count. For example, Porto's car_pm value becomes the row Porto, car, pm, 2040.
Match pieces with a pattern
A regular expression can identify pieces when a single separator is unsuitable. Parentheses form capture groups, matched in the order of names_to. For headings f1824 and m2534, use names_to = c("sex", "age_band") with names_pattern = "([fm])([0-9]+)". The first heading supplies "f" and "1824".
A separator must match the structure you intend. "female_18_34" contains two underscores, so splitting at every underscore produces three pieces. To keep the age band together, names_pattern = "([a-z]+)_(.*)" captures "female" first and "18_34" second. If a constant piece is unwanted, put NA in its position: names_to = c(NA, "mode") with names_sep = "_" drops "count" from count_bike. Removing names_prefix = "count_" is another way to handle that fixed prefix.
Let part of the name become an output column
Plants have height in centimeters and leaf counts at two weeks. Those are two measurements, so keep two output columns:
plants <- tibble(
plant = c("A", "B", "C"),
height_1 = c(8, 10, 9), height_2 = c(11, 13, 12),
leaves_1 = c(3, 4, 3), leaves_2 = c(5, 6, 4)
)
plants |>
pivot_longer(
cols = !plant,
names_to = c(".value", "week"),
names_sep = "_",
names_transform = list(week = as.integer)
)
The special string ".value" makes "height" and "leaves" output column names. values_to is unnecessary because this piece already names the value columns. Each plant now has two rows, one per week: six rows with plant, week, height, and leaves. For plant A in week 2, height is 11 cm and leaf count is 5.
Compare this with an ordinary two-piece split into measure and week. That would put height and leaf count into one value column and produce four rows per plant. Use .value when a piece names the separate variables you need to preserve. The week piece still arrives as text unless you convert it during the pivot or afterward.
Key Takeaways
- Use
names_sepwhen a separator divides the required pieces. - Capture groups in
names_patternfillnames_toin order. - Use
NAto discard an unwanted name piece. - Use
".value"when a name piece should name an output measurement column. - A
.valuepivot can keep measurements with different units separate. - Convert numeric name pieces explicitly.
1.4 Make one column per measurement
pivot_wider() moves values from a names column into headings. It is useful when measurements belonging to one observation are spread across rows, and when a report or comparison needs values side by side.
Name the output cells
library(tidyverse)
labs <- tribble(
~patient, ~test, ~value,
"P1", "glucose", 5.4,
"P1", "sodium", 140,
"P2", "glucose", 6.1,
"P2", "sodium", 138,
"P3", "glucose", 4.9
)
labs |>
pivot_wider(
id_cols = patient,
names_from = test, values_from = value
)
names_from identifies the existing column containing future headings; values_from identifies the existing measurement column. The result has three patient rows and columns patient, glucose, and sodium. Both tests are measured in mmol/L. P3's sodium cell is NA because no matching row supplied a result.
Choose identifiers deliberately
By default, id_cols contains every column outside names_from and values_from. Suppose each test row also includes a different measurement time. Keeping that time as an identifier creates different rows for each test, leaving many empty cells. id_cols = patient makes the intended unit explicit. If the tests belong to distinct visits, include visit too; a patient alone would merge observations that should remain separate.
Resolve more than one value per cell
If P1 has glucose results of 5.4 and 5.8 for the same identifier, the destination cell has two candidates. tidyr warns and produces a list-column. Check the grouping that defines a cell:
labs |>
count(patient, test) |>
filter(n > 1)
The next step depends on the records' meaning. An extra visit needs a visit identifier. Accidental repeated records need cleaning. If the analysis calls for the mean of genuine repeats, use values_fn = mean; the two P1 glucose values then give 5.6. Choosing an arbitrary summary just to remove the warning changes the data without explaining why.
Fill only known absent combinations
values_fill supplies a value where no row matched. In a completed bird survey that records only positive counts, rows S1 heron 3, S1 egret 1, and S2 heron 2 mean that S2 had zero egrets. values_fill = 0 expresses that recording rule. An unperformed lab test is unknown, so its missing result must not become zero. Filling absent combinations also differs from replacing an explicit missing measurement already present in a row.
New headings can be controlled too. names_prefix = "year_" turns year values into names such as year_2023. If names_from includes several columns, names_sep joins their pieces, using an underscore by default.
Widening rainfall years supports mutate(change = `2024` - `2023`). Beta's change is 46 mm; Alpha's is NA because its 2023 measurement is missing. Lengthening and widening can preserve the information without reproducing an identical object: row order can change, absent combinations can appear as NA, and numeric years become text headings again.
Key Takeaways
- Set
names_fromandvalues_fromto existing columns. - Use identifiers that distinguish the observations you intend to keep.
- Investigate repeated identifier-name pairs before summarizing them.
- Fill absent combinations with zero only when zero is their known meaning.
- A pivot round trip may change row order or explicit missing combinations.
2Import text files reliably with readr
A text file carries more choices than its extension reveals. Its header, missing-value codes, separator, decimal mark, and encoding all affect what R reads. Work from a small CSV import to an explicit set of column types, then handle regional conventions and combine matching files. Checks on dimensions and original values make it possible to trust the resulting table and save it in a format that suits its next use.
2.1 Read a file and inspect the result
A CSV file stores records as plain text, usually with a header line and commas between fields. A quoted field such as "Ruiz, Ana" can contain a comma without starting another column. readr::read_csv() reads the file into a tibble; its spelling differs from base R's read.csv().
Read from the project folder
library(tidyverse)
samples <- read_csv("data/samples.csv")
The path starts at the working directory. In an RStudio project, this is normally the project folder. A file-not-found error calls for checking that starting point and the file's location. read_csv() also accepts a URL pointing directly to a CSV file.
Suppose the file contains:
Sample ID,Site Name,temp.C,Depth m,notes
S01,North Pier,14.2,1.5,
S02,East Bay,N/A,2.0,cloudy
S03,West Reef,13.8,,
The import has three rows and five columns. Depth m is numeric, with a missing value in S03. temp.C becomes text because "N/A" is not a number. The other three columns are text, so the first read gives four character columns and one double column.
Tell readr what missing means
The default missing strings are "" and "NA". Add the actual codes used by this file:
samples <- read_csv(
"data/samples.csv",
na = c("", "NA", "N/A")
)
Now temp.C holds 14.2, NA, and 13.8 as numbers. Their available-value mean is 14.0. A code such as "999" can be treated as missing only when it cannot be a genuine value in that column. Replacing valid measurements with NA would silently change the evidence.
Match headers and extra lines
Use skip = 2 when two opening lines contain notes. comment = "#" treats the comment marker and the rest of its line as comment text. For a file with no header, col_names = FALSE gives names X1, X2, and so on. A character vector such as col_names = c("id", "site", "temp") supplies names directly; skip an existing header if you supply replacements.
readr preserves names such as Sample ID. Refer to them in backticks, as in select(samples, `Sample ID`), or rename them. The separate janitor package provides janitor::clean_names(samples), producing sample_id, site_name, temp_c, depth_m, and notes. Base read.csv() normally changes a name like Sample ID to Sample.ID.
Check before analyzing
Read the import message for its row count, column count, delimiter, and chosen types: chr is text, dbl is numeric, lgl is logical, and date is a date. Use glimpse(samples) to inspect the table and spec(samples) to see readr's column specification. Compare a few imported records with the text file. Hide the type message with show_col_types = FALSE after the settings have been checked.
Keep the raw file unchanged and express import decisions in code. Resaving a CSV in a spreadsheet can change dates, leading zeros, or separators before your script ever sees them.
Key Takeaways
- Read paths relative to the working directory.
- Declare missing-value strings used by the file.
- Match header and skip settings to the actual opening lines.
- Check dimensions, types, and sample records after importing.
2.2 Control types and trace failed values
A successful file read can still give a column the wrong type. Type guessing samples values; a schema written in code states what the columns should mean. Use both the intended meaning and the original text when deciding how to parse a file.
Understand the guess
readr normally samples 1,000 rows spread through the file, ignoring missing entries. It recognizes logical values first, then numbers, ISO dates or date-times, and otherwise text. Whole-number measurements are normally guessed as doubles, not integer columns. guess_max = 5000 increases the sample, but it does not explain a missing-value code or protect a numeric-looking identifier.
A column containing "12 kg" or "45%" is text because the entries include more than a plain number. A rare text entry can also lie outside the sampled rows. Reading more rows can reveal that entry, but you still need to decide what it means.
Specify columns by name
library(readr)
depths <- read_csv(
"data/depths.csv",
col_types = cols(
site = col_character(),
depth_m = col_double(),
visit = col_integer()
)
)
problems(depths)
Unlisted columns are still guessed. cols_only() reads only the named columns. cols(.default = col_character()) reads all columns as text for inspection. Compact specifications such as "ccd" mean character, character, double, in column order.
Choose a type from the data's meaning. A code such as "02138" needs col_character() to retain its leading zero. It identifies something; adding codes has no useful meaning. col_logical() handles true/false values. col_date(format = "%d/%m/%Y") handles a known day-first date. col_factor(levels = c("low", "medium", "high")) declares the allowed categories and their order. A value outside those levels produces a parsing problem. col_skip() leaves a column out.
Find the text that failed
If depth_m contains "deep", it cannot be read as a double. readr warns and places NA in that cell. problems(depths) identifies the row, column, expected type, and actual text. That NA arose during parsing; it is not evidence that the source cell was empty.
Inspect the failed text before changing the parser. If meanings are mixed, import the column as character and convert after examining the entries. Silencing a warning leaves the failed values missing.
Extract a number without changing its meaning
parse_number("12 kg")
parse_number("1,250")
parse_number("45%")
With the default locale, these return 12, 1250, and 45. parse_number() reads the first number while discarding surrounding text and recognizing grouping marks. It does not convert a percentage to a proportion: divide 45 by 100 to get 0.45 when a proportion is needed. as.numeric("1,250") instead returns NA with a warning because the comma is not valid in a plain R numeric string. Preserve the unit's meaning when you remove its written label.
Key Takeaways
- Use explicit types for identifiers and columns whose meanings are known.
- Inspect
problems()when parsing creates missing values. - Read as text when you need to examine mixed entries before conversion.
parse_number()extracts numbers but does not rescale percentages.- Increasing
guess_maximproves sampling, not the meaning of the schema.
2.3 Match separators, number formats, and encoding
The label "CSV" does not tell you every detail of a file. The field separator, decimal mark, text encoding, and date order are separate choices. Read a few raw lines to see which conventions the exporter used.
Choose the field separator
| File structure | readr function |
|---|---|
| Comma between fields | read_csv() |
| Semicolon fields and decimal commas | read_csv2() |
| Tab between fields | read_tsv() |
| Another separator, such as a pipe | read_delim() |
| Fixed character positions | read_fwf() |
For a pipe-delimited file, the separator argument is the literal character "|". A fixed-width file instead gives each column a fixed span of characters.
Read decimal commas correctly
A decimal comma would conflict with commas used as field separators. Many spreadsheet exports solve this by separating fields with semicolons:
product;price;quantity
Coffee;3,50;2
Tea;2,75;4
library(tidyverse)
prices <- read_csv2("data/prices.csv")
prices |> mutate(spend = price * quantity)
The numeric prices in R are 3.5 and 2.75. The row totals are 7 and 11, giving 18 overall. read_csv2() sets semicolon fields and a decimal-comma locale. Reading this file with read_csv() instead splits at the decimal commas and misreads the structure. A header imported as one name containing semicolons is a useful sign of a wrong delimiter.
Set the number convention separately
Not every semicolon file uses decimal commas. If the file writes 3.50, use read_delim("data/prices.csv", delim = ";") with its default decimal-point locale. For an explicit decimal-comma locale:
comma_locale <- locale(decimal_mark = ",", grouping_mark = ".")
prices <- read_delim(
"data/prices.csv", delim = ";", locale = comma_locale
)
parse_number("1.234,5", locale = comma_locale)
The parsed number is 1234.5. The default readr locale uses a point for decimals and a comma for grouping. A grouping mark separates digit groups; it is not the decimal boundary. Check actual numeric values after import, not just the number of columns.
Keep text and dates readable
readr expects UTF-8 text by default. Older Latin-1 bytes interpreted as UTF-8 can produce invalid or garbled letters. guess_encoding("data/file.csv") suggests encodings; use locale(encoding = "latin1") when that matches the file. UTF-8 decoded as Latin-1 can show "é" in place of "é". The encoding controls characters, independently of the delimiter and decimal mark.
The date "03/04/2025" could mean April 3 or March 4. For known day-first records, set col_date(format = "%d/%m/%Y"). A number locale alone does not settle date order.
For output, write_csv2() writes semicolon fields with decimal commas. write_excel_csv() and write_excel_csv2() include a UTF-8 marker that helps Excel recognize accented text. Choose the output to match the receiving program's settings.
Key Takeaways
- Choose the parser from the separator and numeric convention together.
- Use
locale()to state decimal, grouping, and encoding settings. - Check ambiguous dates with an explicit date format.
- Choose a matching writer for decimal-comma or Excel recipients.
2.4 Combine files and choose an output format
A folder of monthly files often represents one dataset. Reading them together is useful only when the columns have the same names and meanings. Keep a source column so you can trace each imported row back to its file.
Find paths and read together
library(tidyverse)
files <- list.files(
"data", pattern = "sales[.]csv$", full.names = TRUE
)
sales <- read_csv(files, id = "file")
sales |> count(file)
list.files() returns matching paths. The pattern here matches names ending in the literal text "sales.csv"; [.] means a literal period and the final dollar sign marks the end. full.names = TRUE retains the folder in each path so the reader can find files from the project directory.
read_csv() accepts the path vector and stacks the records. id = "file" adds their origin. For files 01-sales.csv, 02-sales.csv, and 03-sales.csv with 120, 95, and 140 rows, the combined table has 355 rows. count(file) should recover those three counts. parse_number(basename(file)) extracts the month number when that is the naming convention.
Inspect the path list too: it should include exactly the intended files. Check column types after combining. A renamed or extra column signals a mismatch to resolve before treating the files as one consistent table.
Type small supporting tables
Use tibble() for columns or tribble() for a row-oriented layout:
stations <- tibble(
station = c("Alpha", "Beta"), elevation_m = c(120, 455)
)
station_check <- tribble(
~station, ~elevation_m,
"Alpha", 120,
"Beta", 455
)
Both tables carry the same two station records. These forms are convenient for small lookups and examples used to check an import pipeline.
Save for the next reader
| Format | Main strength | What to remember |
|---|---|---|
| CSV | Plain text read by many programs | Types and factor level order are not stored |
| RDS | Preserves the R object | Intended for use in R |
| Parquet | Typed, compressed columns for many tools | Requires a compatible reader |
dir.create("results", showWarnings = FALSE)
write_csv(sales, "results/sales.csv")
write_rds(sales, "results/sales.rds")
arrow::write_parquet(sales, "results/sales.parquet")
write_csv() writes missing values as NA by default. On reading a CSV again, types must be inferred or declared; a factor's ordered levels do not survive in the text. read_rds() restores the saved R object, including factor levels. arrow::read_parquet() reads the typed Parquet data, which can also be shared with Python, Julia, and database tools.
Keep raw inputs in their own folder, the import and reshaping steps in a script, and processed outputs in a separate folder. This prevents an output from replacing its own input and lets the same steps run on the next delivery of data.
Key Takeaways
- Check file paths and compatible column meanings before stacking files.
- Retain each row’s source with
id. - Choose CSV for broad text exchange, RDS for R objects, or Parquet for typed columnar data.
- Preserve raw inputs and write processed results separately.
3Get data out of spreadsheets
Spreadsheets mix data with conveniences for people: titles, notes, multiple tabs, colors, and formulas. Reading the intended rectangle is only part of the job; the imported columns must retain their meaning. Learn to choose sheets and types in Excel and Google Sheets, preserve the origin of combined records, and save the exact data used from a live source. Writing results back also requires a clear destination.
3.1 Read the cells that contain the table
An Excel workbook is a container for sheets, not necessarily one analysis table. A sheet may mix notes, titles, several tables, and formatting. Use readxl to identify the data block and bring its values into R without requiring Excel to be installed.
Choose the workbook and sheet
library(tidyverse)
library(readxl)
excel_sheets("data/fieldwork.xlsx")
fieldwork <- read_excel("data/fieldwork.xlsx", sheet = "2024")
readxl is installed with the tidyverse but needs its own library(readxl) call. read_excel() detects .xls or .xlsx; read_xls() and read_xlsx() select those formats directly. sheet = 2 reads the second sheet. Omitting sheet reads the first.
Select a rectangle
fieldwork <- read_excel(
"data/fieldwork.xlsx",
range = "2024!B3:E40",
na = c("", "N/A", "-"),
col_types = c("text", "date", "numeric", "numeric")
)
The rectangle has four columns; its first row supplies headers by default. A range such as "B3:F40" spans five columns. range takes precedence over sheet, skip, and n_max, so choose the rectangle itself when notes surround the table. Without a range, skip = 2 ignores two opening rows and n_max = 100 limits the number of data rows.
readxl treats blank cells as missing by default. List other actual missing codes in na. Its type vocabulary is text such as "numeric", "text", "date", "logical", "guess", "skip", or "list", rather than readr's col_double() functions. Imported date columns arrive as date-times. To provide names, use a vector in col_names and skip the original header; otherwise the old header is read as data.
Combine sheets without losing their origin
For two sheets with the same columns:
a <- read_excel("data/fieldwork.xlsx", sheet = "2023") |>
mutate(year = 2023)
b <- read_excel("data/fieldwork.xlsx", sheet = "2024") |>
mutate(year = 2024)
fieldwork <- bind_rows(a, b)
If the sheets have 48 and 52 rows, the result has 100, and year records where each row came from. Check that the columns mean the same thing on both sheets.
Preserve meaning beyond displayed cells
Color, bold text, and comments do not become data columns. A formula supplies its last saved calculated value. For a merged block, only the top-left cell contains the value; the other positions become missing. If red means "unverified", store that status explicitly in a column.
Excel dates are day counts with a workbook date system. Prefer importing the column as "date". In the common 1900 system, as.Date(45658, origin = "1899-12-30") gives January 1, 2025; the origin must match the workbook.
Write an Excel result with writexl::write_xlsx(fieldwork, "results/summary.xlsx"). A named list, such as list(rain = rain_long, stations = stations), writes separate named worksheets. For styling or editing an existing workbook, openxlsx offers additional controls.
Key Takeaways
- List sheets before choosing one by name or position.
- Use a range to isolate a table from titles and notes.
- Specify readxl types with its text type names.
- Make formatting-based meaning explicit in columns.
- Add sheet identifiers before stacking compatible sheets.
3.2 Read a shared sheet and preserve the snapshot
Google Sheets is a live data source: its contents can change even when your R script stays the same. googlesheets4 reads a spreadsheet into a tibble using its full URL or the ID between /d/ and /edit in the address.
Choose public or authenticated access
library(tidyverse)
library(googlesheets4)
gs4_deauth()
Use this mode for a sheet that anyone with its link can view. It tells the package not to request a login token. A private spreadsheet needs gs4_auth() and an account with permission to read it. Authentication normally opens a browser for sign-in and consent; cached credentials can be reused in later sessions. Signing in does not itself grant access to a spreadsheet the account cannot read.
State the sheet and column meanings
Suppose a public volunteer spreadsheet records site, date, species, and count. Assign its address to sheet_url, then read it:
counts <- read_sheet(
sheet_url, sheet = "Counts",
col_types = "cDci"
)
"cDci" gives text, date, text, and integer. Other useful letters are d for double, l for logical, T for date-time, ? for guessing, and _ or - to skip a column. This is a compact string with one entry per column, not readxl's vector of full type names.
read_sheet() and range_read() name the same reading operation. sheet_names(sheet_url) lists worksheet names. Select a worksheet by name or position, or provide a range such as "Counts!A1:D50". Other familiar arguments include col_names, na, skip, and n_max; the default worksheet is the first visible one.
Inspect mixed entries
A count column may include text such as "about 10". Read that column as text with c when the written entry matters, then inspect before converting. parse_number() can extract 10, but it does not preserve the qualifier "about" in the resulting number. The choice to turn an approximate count into a numeric count needs an explicit interpretation. Check the column types and a few rows after each import.
Save what the analysis used
dir.create("snapshots", showWarnings = FALSE)
write_csv(counts, "snapshots/counts-2026-11-05.csv")
A dated snapshot lets you return to the data used for a particular result. Reading the live sheet again later may include added rows or edited counts. Record the extraction date alongside the snapshot, and retain the source address in the analysis script. Reproducibility needs the data as well as the code.
Write a result back
An authenticated account with edit access can use write_sheet(totals, ss = sheet_url, sheet = "Totals"). This adds the target worksheet if absent or replaces it if it already exists, clearing its previous contents and formatting. gs4_create() creates a new spreadsheet. Public read access and successful import do not supply edit access; switch from deauthorized reading to authenticated writing when needed.
Key Takeaways
- Use deauthorized access for public reading and an authorized account for private sheets.
- Match compact type letters to the columns in their actual order.
- Save a dated snapshot when a live sheet supplies analysis data.
- Writing requires edit access and replaces an existing target worksheet.
4Query databases from R
A database can process records where they are stored and return a compact answer. Use DBI to connect and request data, then reuse dplyr skills through dbplyr to build queries without copying entire tables into R. Reading the generated SQL makes the execution visible. Pay attention to when a query runs, where a function can execute, and how missing values and row order behave when the work happens in a database.
4.1 Connect to a database and request a result
A database stores records in named tables and answers queries in SQL, the Structured Query Language. Tables resemble data frames, but their storage and execution can live outside R. This lets a database hold and process far more data than you can comfortably load into local memory.
Match DBI to a database backend
DBI supplies a shared interface; a backend package implements it for a particular system.
| System | Example backend |
|---|---|
| PostgreSQL | RPostgres |
| MySQL or MariaDB | RMariaDB |
| SQLite | RSQLite |
| DuckDB | duckdb |
| BigQuery | bigrquery |
| Systems with an ODBC driver | odbc |
Client-server systems such as PostgreSQL, MySQL/MariaDB, and SQL Server run on a server. Cloud systems include BigQuery, Snowflake, and Redshift. SQLite and DuckDB can run inside the R process and use local files. An index can make particular database lookups faster; a table is not simply an R object saved under a different name.
Try a temporary local database
library(DBI)
con <- dbConnect(duckdb::duckdb())
rain <- data.frame(
station = c("Alpha", "Alpha", "Beta", "Beta", "Beta"),
year = c(2022, 2024, 2022, 2023, 2024),
rainfall_mm = c(812, 790, 640, 655, 701)
)
dbWriteTable(con, "rainfall", rain)
dbListTables(con)
This DuckDB database is temporary. To keep data between sessions, connect to a file with dbConnect(duckdb::duckdb(), dbdir = "climate.duckdb"). dbWriteTable() copies an R data frame into a database table. dbReadTable(con, "rainfall") brings the complete table back, which is reasonable for this five-row example.
For CSV files that are too large to read into R first, duckdb::duckdb_read_csv(con, "trips", files) loads the paths in files directly into a DuckDB table.
Fetch only the requested records
dbGetQuery(con, paste(
"SELECT station, rainfall_mm FROM rainfall",
"WHERE year = 2024"
))
The result is a local data frame containing Alpha 790 and Beta 701. SELECT chooses columns, and WHERE restricts records before they are returned. dbGetQuery() retrieves query results; dbExecute() runs a statement that changes the database, such as creating an index, and reports affected rows.
Connect and close deliberately
A server connection also needs its address, database, and credentials:
con_server <- dbConnect(
RPostgres::Postgres(), host = "db.example.org",
dbname = "climate", user = "ana",
password = Sys.getenv("PGPASSWORD")
)
Keep passwords out of scripts by reading an environment variable or using a system keychain. Connection details belong to the system you can access; a backend alone does not create a server account.
Finish the local example with dbDisconnect(con) and close a server connection after its queries are done. On a large table, filter or summarize remotely before fetching. Reading every row with dbReadTable() transfers the memory burden straight back to R.
Key Takeaways
- DBI supplies the interface; a backend connects it to a particular system.
- A temporary in-process database differs from a persistent database file.
- Fetch a query result with
dbGetQuery()and reservedbExecute()for statements. - Filter large tables remotely and disconnect when finished.
4.2 Keep database work remote until the result is small
dbplyr lets dplyr verbs describe a database query. The familiar code stays in R, while the database executes the translated work. The important change is the object you are working on: a lazy reference is not a local copy of the table.
Refer to a table
library(dplyr)
library(dbplyr)
rain_db <- tbl(con, "rainfall")
Here con is an open DBI connection holding the five rainfall records: Alpha 2022 812 and 2024 790; Beta 2022 640, 2023 655, and 2024 701. tbl() records where the data live. Printing rain_db requests a preview, not the whole table. Its display can show an unknown row count because counting all records would require another query.
Build, then collect
rain_query <- rain_db |>
filter(year >= 2023) |>
group_by(station) |>
summarize(mean_mm = mean(rainfall_mm, na.rm = TRUE)) |>
arrange(desc(mean_mm))
result <- collect(rain_query)
The filter leaves Alpha's 790 and Beta's 655 and 701. The database averages each group and sorts the results. collect() runs the full query and returns a local tibble: Alpha 790, then Beta 678. Assigning the pipeline to rain_query builds the query description; it does not first copy the rainfall table into R.
Filtering, selecting columns, and summarizing before collecting reduce the amount transferred. If you collect first, later dplyr steps run locally and the complete remote table has already crossed the connection. Once a small result is local, use ordinary R functions or ggplot2 on it.
Know the translation boundary
dbplyr translates arithmetic, comparisons, &, |, if_else(), case_when(), is.na(), and common summaries such as mean(), sum(), min(), max(), and n(). An unknown function name can be passed into SQL unchanged. That succeeds only if the database knows a matching function. A function you wrote in R cannot execute inside the database merely because it appears in mutate().
For a custom R calculation, use supported remote steps to reduce the data, collect the manageable result, and then run the function locally. This keeps the data movement visible.
Count and order explicitly
A database table has no fixed row order. Use arrange() when ordering is part of the question; head(10) limits records but does not itself select a meaningful "first" ten. nrow() on a lazy table returns NA; request a count with summarize(n = n()) |> collect() or use count().
copy_to(con, df) sends a local data frame into a database. For a table in another schema, use tbl(con, in_schema("sales", "orders")). dbplyr adapts common dplyr operations to systems such as DuckDB, SQLite, and PostgreSQL. Their SQL functions and supported features still matter when an operation goes beyond the shared verbs.
Key Takeaways
tbl()creates a reference, and verbs build a lazy query.collect()executes the query and returns its result to R.- Reduce rows and columns before transferring data.
- Run custom R functions locally after reducing the remote data.
- Request counts and ordering explicitly.
4.3 Read the query behind the pipeline
show_query() displays the SQL built by a dbplyr pipeline. It does not fetch the result. Reading the query helps you see which columns and records the database will process and where the work happens.
Map verbs to clauses
A basic query is written with SELECT, FROM, WHERE, GROUP BY, and ORDER BY in that order. Uppercase keywords are a reading convention; SQL keywords are not case sensitive.
| dplyr operation | Main SQL form |
|---|---|
select(), rename(), mutate(), summarize() | Expressions after SELECT; AS names results |
filter() on source records | WHERE |
group_by() with a summary | GROUP BY |
arrange() | ORDER BY; descending order uses DESC |
left_join() | LEFT JOIN ... ON |
For a lazy table rain_db, inspect a station summary:
rain_db |>
filter(year >= 2023) |>
group_by(station) |>
summarize(mean_mm = mean(rainfall_mm, na.rm = TRUE)) |>
arrange(desc(mean_mm)) |>
show_query()
A representative query is:
SELECT station, AVG(rainfall_mm) AS mean_mm
FROM rainfall
WHERE year >= 2023
GROUP BY station
ORDER BY mean_mm DESC
The database selects recent records, groups by station, averages rainfall, and sorts the group results. The exact quoting, numeric spelling, whitespace, or use of subqueries depends on the backend and dbplyr version.
Read comparisons and missing values
R's == becomes SQL's =, & becomes AND, | becomes OR, and %in% becomes IN. SQL string literals use single quotes, as in station = 'Alpha'. These symbols describe the same intended row conditions in a different language.
SQL uses NULL where R uses NA. Test missingness with IS NULL; is.na(rainfall_mm) translates to rainfall_mm IS NULL. Equality to NULL does not select missing records, because the comparison is unknown.
SQL aggregates such as AVG() ignore NULL. Writing mean(rainfall_mm, na.rm = TRUE) makes that behavior explicit in R code. Leaving out na.rm = TRUE can trigger a dbplyr warning; it does not make SQL propagate missing values as R's default mean() would. If every value is missing, an average remains unknown.
Distinguish record filters from group filters
A filter before a summary chooses records to include. A filter after the summary can become HAVING, which chooses among summarized groups. For example, keeping groups with a mean above a threshold differs from removing individual low readings before averaging.
A filter on a column created by mutate() can require a subquery: standard SQL processes WHERE before the new SELECT alias is available. Nested SQL can therefore express a simple dplyr pipeline correctly.
You can also supply SQL directly with dbGetQuery(). To keep a SQL query lazy and extend it with dplyr, use tbl(con, sql("SELECT * FROM rainfall")). Both routes use the same connection; choose the one that clearly expresses the operation.
Key Takeaways
- Use
show_query()to inspect SQL without collecting data. - Read
SELECT,WHERE, grouping, and ordering as different query jobs. - Test SQL missing values with
IS NULL. - Distinguish filters on individual records from filters on summarized groups.
5Handle large datasets with Arrow and Parquet
A large file may contain far more data than a question needs. Parquet stores columns so a query can skip unnecessary reading, and partitioned folders can exclude entire groups of files. Arrow runs dplyr operations on these datasets before results become local R tables. Learn to choose a useful storage layout, convert a CSV, and plan queries around both the size of their answers and the memory needed while they run.
5.1 Store large tables in partitioned Parquet
A large CSV query generally scans text to find the records and fields it needs. Numbers and dates must be interpreted during reading. Parquet stores typed, compressed columns and lets a reader skip unneeded columns and data chunks.
Separate the format from the engine
Parquet is an open, binary format for tabular files. You cannot read it as ordinary text, but many languages and database systems support it. Its column-based layout lets a query read selected variables, while chunk metadata can help skip irrelevant data.
Apache Arrow provides column-based data structures and a computing engine. The R arrow package connects dplyr code to that engine. Parquet is a storage format; Arrow executes queries against files without first making one large R data frame.
The Seattle library checkout example has about 9 GB of CSV text and 41,389,465 rows. A dataset of that size can exceed comfortable local memory even when a question needs only a year's totals.
Open a CSV without collecting it
library(dplyr)
library(arrow)
checkouts <- open_dataset(
"data/seattle-library-checkouts.csv", format = "csv",
col_types = schema(ISBN = string())
)
This opens a dataset reference. The type declaration keeps ISBN as text even if sampled entries look numeric. CSV inference samples data, so rare text can otherwise appear only when the full query runs. Check the schema and important identifiers before conversion.
Choose useful partitions
Partitioning divides a dataset into files according to a column's values. Hive-style folders encode these values, such as CheckoutYear=2021/part-0.parquet. Reading the directory reconstructs the year column from those folder names.
Choose a column you often filter on, with a moderate number of values. Year can be useful for year-specific queries. A customer identifier with a million values creates too many small partitions. Daily partitions for 2015 through 2024 create 3,653 date folders. More partitions are helpful only when the saved work outweighs the extra file overhead.
As practical guidelines, aim for files around 20 MB to 2 GB and avoid layouts producing more than 10,000 files. These are design guides, not promises about the best layout for every machine or query.
Write the dataset
checkouts |>
group_by(CheckoutYear) |>
write_dataset(path = "data/seattle-pq", format = "parquet")
The grouping supplies the partition column. You can also name partitioning = "CheckoutYear" directly in write_dataset(). For the library example, the year-based conversion produces 18 files around 100–300 MB each, totaling roughly 4 GB. Conversion pays an upfront cost so later queries can avoid repeated text parsing and skip irrelevant partitions.
For one data frame that fits in memory, write_parquet() and read_parquet() handle a single file. Use CSV for small, widely exchanged text tables, RDS for an R object reloaded in R, and Parquet for typed data shared across tools or queried repeatedly. Partitioning is a further storage choice when multiple files help the workload.
Key Takeaways
- Parquet stores compressed, typed columns; Arrow supplies the query engine.
- Open a large CSV as a dataset and protect identifiers with declared types.
- Partition by a frequently filtered variable with a moderate number of values.
- Balance skipped work against the overhead of many small files.
- Use
write_dataset()for partitioned storage andwrite_parquet()for a single file.
5.2 Collect the answer from a large dataset
Opening a Parquet directory reads metadata about its files, columns, and types. It does not bring every record into R. Write the query against that dataset, let Arrow reduce the data, and collect the answer you can use locally.
Build a lazy query
library(dplyr)
library(arrow)
seattle_pq <- open_dataset("data/seattle-pq")
glimpse(seattle_pq)
monthly_query <- seattle_pq |>
filter(CheckoutYear == 2021, MaterialType == "BOOK") |>
group_by(CheckoutMonth) |>
summarize(TotalCheckouts = sum(Checkouts)) |>
arrange(CheckoutMonth)
monthly <- collect(monthly_query)
The verbs describe a query. collect() makes Arrow execute it and returns an R tibble. For the library data, the result has 12 monthly rows. glimpse() shows the dataset's column structure without loading the whole dataset.
Explain the work saved
A year-partitioned directory lets the filter use the 2021 folder and skip other years. Columnar storage lets the query read the fields it needs for filtering, grouping, and summing, leaving unrelated variables unread. Compression reduces disk traffic as well. In the book's example, this query took about 11.4 seconds on CSV and 0.06 seconds on partitioned Parquet. Timings depend on the data, storage, and computer; the reasons for avoiding unnecessary reads remain useful.
Budget for execution as well as the result
The collected result must fit in memory, and Arrow also needs working memory to execute operations. Sorting a large input can be demanding even if a later step returns few rows. Filter and summarize early so fewer records reach expensive operations.
When the result size is uncertain, request a count before collecting the detailed records:
seattle_pq |>
filter(CheckoutYear == 2021, MaterialType == "BOOK") |>
summarize(n = n()) |>
collect()
This collects a one-row count. Collecting the entire dataset first would recreate the memory problem. A small final row count is useful information, but it does not measure every intermediate operation's memory use.
Handle a function the engine cannot run
Arrow supports many dplyr operations and R functions, but a dataset query stops if an expression has no supported translation. Reduce the dataset using supported filters and summaries, collect a manageable result, and continue with the required R function locally. This makes the change of execution location deliberate.
If the needed operation is supported by DuckDB, hand the dataset to that engine:
library(dbplyr)
duck_query <- seattle_pq |>
to_duckdb() |>
filter(CheckoutYear == 2021) |>
count(MaterialType)
show_query(duck_query)
collect(duck_query)
to_duckdb() exposes Arrow data to DuckDB without copying the entire dataset into R. The pipeline then follows dbplyr's SQL translation rules. to_arrow() provides the return route. Across local data frames, database tables, and Arrow datasets, the verbs look similar; the engine and the point where data become local determine what can run and how much memory is needed.
Key Takeaways
- Build a dataset query lazily and collect its reduced result.
- Partition filters and column selection save different kinds of reading.
- Allow memory for intermediate execution as well as the final tibble.
- Use supported reductions before running a local R-only function.
- Use
to_duckdb()when DuckDB supports an operation needed on Arrow data.
Tidy Data and Data Import in R examples
1Reshape a table without losing its meaning
15 steps
- 1IntroductionGive each measurement a place
A rainfall table can store years as headings even though year is a variable. Tidy data gives each variable its own column, which is what plots and models expect. Start by deciding what one row should mean: one station measured in one year. Then use a pivot to move headings into a year column, preserve missing measurements when they matter, and compare years side by side when needed. The same choices extend to names containing several variables and to repeated measurements competing for one output cell.
- 2ExplanationName the unit and variables
One observation collects values for the same unit at the same time. For rainfall, a station-year row has
station,year, andrainfall_mm.Tidy data puts each variable in a column, each observation in a row, and each value in a cell. The identifier tells you which observation a measurement belongs to. A station lookup with elevation describes stations, so it belongs in its own station-level table.
- 3ChallengeDecide what should stay separate
A table has one row per plant with
plant,height_cm, andleaf_count. Must both measurements be stacked into onevaluecolumn to make it tidy?---reveal---
No. Height and leaf count are different variables, and each already has a column. They describe the same plant observation, with different units and meanings. A long shape is useful only when it represents the intended variables clearly; row count alone does not decide tidiness.
- 4ExampleCreate a wide rainfall table
Load the packages and create the input for the next steps:
library(tidyverse) rain_wide <- tibble( station = c("Alpha", "Beta"), `2022` = c(812, 640), `2023` = c(NA, 655), `2024` = c(790, 701) )The three year headings hold values of a year variable. Each station currently occupies one row, so moving to station-year observations should create three rows per station.
- 5ExampleLengthen and convert the year
Keep the station identifier outside the pivot:
rain_long <- rain_wide |> pivot_longer( cols = !station, names_to = "year", values_to = "rainfall_mm", names_transform = list(year = as.integer) )There are six rows and three columns. Station values repeat. The new year column is integer because of
names_transform; without conversion, the old headings would arrive as text. - 6Key InsightA missing row can carry information
Alpha’s 2023 measurement is
NA. Keeping that row preserves the fact that this station-year has no recorded measurement. Addingvalues_drop_na = TRUEleaves five rows instead of six.For a chart history, empty weekly ranks after a song left the chart can be dropped. For a measurement-coverage question, retain the missing rows. Available-value means can still use
na.rm = TRUEwithout deleting those observations from the table. - 7ChallengePredict the output before running
A table contains three machines and four hourly reading columns. Two reading cells are
NA. How many rows result before and after addingvalues_drop_na = TRUE?---reveal---
The ordinary pivot gives 12 rows: four hours for each of three machines. Dropping the two missing readings gives 10 rows. The machine identifier repeats on those rows; it must stay outside the reading-column selection so each measurement retains its owner.
- 8ExampleSeparate mode from period
The traffic headings
bike_am,bike_pm,car_am, andcar_pmeach contain two variables. For a tabletrafficwith acityidentifier:traffic |> pivot_longer( cols = !city, names_to = c("mode", "period"), names_sep = "_", values_to = "count" )The first piece becomes mode and the second becomes period. Two cities contribute eight rows, with one count per city-mode-period.
- 9TipKeep an internal separator inside its value
A heading such as "female_18_34" has three underscore-separated pieces, but the intended variables may be sex and age band. Use
names_to = c("sex", "age_band")withnames_pattern = "([a-z]+)_(.*)"to keep "18_34" together.Each parenthesized capture group supplies one named output piece in order. Use a separator only when splitting at every matching separator gives the pieces you actually need.
- 10ExampleKeep height and leaves in different columns
For a table
plantswithplant,height_1,height_2,leaves_1, andleaves_2, use:plants |> pivot_longer( cols = !plant, names_to = c(".value", "week"), names_sep = "_" ).valueturns the first piece into output namesheightandleaves. The second supplies week. Three plants produce six plant-week rows, keeping centimeters and leaf counts in separate columns. - 11ChallengeRead the pieces in order
Columns are
length_1,length_2,mass_1, andmass_2. A learner choosesnames_to = c("week", ".value"). What needs to change to keep separate length and mass columns?---reveal---
Use
c(".value", "week"). The first name piece is the measurement name, so it must supply the output column names. The second piece is the week. Reversing those roles would use the week numbers as measurement headings and put measurement names in the week column. - 12ExampleBring the years side by side
Use the long rainfall table created earlier:
rain_compare <- rain_long |> pivot_wider( id_cols = station, names_from = year, values_from = rainfall_mm ) |> mutate(change = `2024` - `2023`)stationidentifies each output row. Beta’s change is 46 mm, from 655 to 701. Alpha’s change is missing because its 2023 rainfall is unknown. Widening does not supply a measurement that was never recorded. - 13ExplanationResolve two values for one cell
A patient has two glucose readings, 5.4 and 5.8, for the same identifier. A wider pivot has two candidates for one cell and can produce a list-column.
Find these pairs with
count(patient, test) |> filter(n > 1). If the readings belong to different visits, include visit in the identifier. If the intended result is a mean of real repeats,values_fn = meangives 5.6. The choice follows the meaning of the records. - 14ChallengeChoose identifiers and missing values together
A measurement table has one row per plant-week-variable and includes separate height and mass variables. Some measurements were not made. How should it be widened to one row per plant-week, and should missing cells become zero?
---reveal---
Use plant and week together as identifiers, the variable names for headings, and the measurements for values. Leave missing cells as
NA: an unmade measurement is unknown. Zero filling would assert a known zero height or mass that the records do not establish. - 15RecapTrace each output cell to its record
The meaning of an output cell comes from its variable and observation. A longer pivot extracts heading information; a wider pivot places measurements beside each other using identifiers. Before accepting a reshaped table, inspect the row count, identifier columns, types, and missing combinations. If a cell has several candidate values, resolve what the repeats mean before choosing how to represent them.
2Read, check, and combine text files
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake the file’s conventions explicit
- 2ExampleRead the original text first
- 3ExampleRead and inspect the table
- 4ChallengeKeep the header out of the data
- 5ExplanationProtect meaning with column types
- 6ExampleTrace a failed numeric reading
- 7ChallengeExtract and scale a percentage
- 8ExampleMatch a decimal-comma file
- 9ExplanationSet conventions independently
- 10ChallengeChoose the parser from the raw line
- 11ExampleFind all intended files
- 12ExampleCheck each file’s contribution
- 13ConnectionSave for the next use
- 14ChallengePlan the complete monthly import
- 15RecapCheck structure and meaning together
3Bring spreadsheet tables into R
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSeparate the table from the spreadsheet
- 2ExampleList worksheets before choosing
- 3ExampleRead the rectangle with its headers
- 4Key InsightMake displayed meaning into data
- 5ChallengeCombine year sheets with their identities
- 6ExplanationChoose the access mode
- 7ExampleRead a public counts worksheet
- 8TipSave the input before it changes
- 9ChallengeWrite to the intended worksheet
- 10ChallengePreserve a repeatable multi-sheet analysis
- 11RecapRetain values, origins, and time
4Build a query and collect its result
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAsk the database for an answer
- 2ExampleCreate a temporary database
- 3ExampleRetrieve selected records
- 4ChallengeChoose the right side of the transfer
- 5ExampleBuild a lazy dplyr query
- 6ExampleExecute and collect the small result
- 7TipDo not infer size or order from a preview
- 8ChallengePlace the custom R step
- 9ExampleInspect the SQL without fetching
- 10Key InsightMissing values need a SQL test
- 11ChallengeDistinguish records from group results
- 12ChallengeOrder the workflow and close the connection
- 13RecapKnow which object is local
5Query large files through Arrow
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionRead less data to answer a large-data question
- 2ExplanationSeparate storage from execution
- 3ExampleOpen the CSV and protect an identifier
- 4ExampleWrite year-based Parquet partitions
- 5ChallengeChoose a manageable partition key
- 6ExampleBuild the monthly query
- 7ExampleCollect the monthly totals
- 8Key InsightA small answer still needs working space
- 9ConnectionChange engines deliberately
- 10ChallengeFix the query without collecting everything
- 11RecapMatch the storage layout to the query
Tidy Data and Data Import in R practice questions
Set 1: Build and check import and query pipelines10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
C5:F5 and whose data end at row 24. What readxl range includes exactly the headers and data?Show answerHide answer
C5:F24 does both while excluding the note. Starting at C6 skips the real headers, so default header reading would turn the first record into column names instead of retaining it as data.Question 3 of 10
tree, height_1, height_2, diameter_1, and diameter_2. The two measurements must remain separate columns, with one row per tree-week. What names_to setting fits?Show answerHide answer
.value turns it into an output column name. The second piece supplies week. Using "measure" instead stacks height and diameter in one value column; reversing the pieces would make week numbers into measurement column names.Question 4 of 10
Show answerHide answer
Question 5 of 10
read_csv() was told to read volume_ml as double. The import reports a problem for the original text "trace". What happened to that cell, and what should be inspected next?Show answerHide answer
NA, with a warning. problems(df) exposes the offending text and its location so you can decide what it means. readr does not silently change "trace" into zero or remove the row to make the numeric column valid.Question 6 of 10
id = "source". What result should its checks show?Show answerHide answer
id argument adds one source field, not one column per input file.Question 7 of 10
Show answerHide answer
Question 8 of 10
tbl(con, "measurements") create when con is a database connection?Show answerHide answer
tbl() identifies a database table for lazy querying. It does not download every row into R; dplyr verbs can describe work on the remote table. A printed preview can look like a data frame, but seeing sample rows does not mean the complete table has become a local object.Question 9 of 10
result is missing. What SQL condition expresses this?Show answerHide answer
NULL and tests them with IS NULL. A comparison such as result = NULL evaluates as unknown, so it does not retain missing records in a WHERE filter. Testing the text "NA" would instead ask about a literal string, not SQL missingness.Question 10 of 10
Show answerHide answer
Set 2: Choose layouts and reliable import settings10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
sensor, 2021, and 2022; the year columns contain annual energy use in kJ. What reshaping makes year available as a variable?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
NA. After lengthening those five columns with values_drop_na = TRUE, how many rows remain?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
walk_day, walk_night, bus_day, and bus_night. What names_to and names_sep settings create columns called mode and period?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
item;mass_kg and the row cable;6.25. What reader matches both the separator and the written number?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
wk1, wk2, and wk10. What settings create numeric values 1, 2, and 10 in a new week column?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
con is open. Which function returns a data frame from a SQL SELECT query?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 3: Diagnose structure and import mistakes10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
parcel, mass_kg, and volume_l. A colleague proposes stacking mass and volume into one unlabeled value column. How should the current layout be judged?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
plot, height_cm_1, height_cm_2, leaf_count_1, and leaf_count_2. The output needs one row per plot-week, integer weeks, and separate height_cm and leaf_count columns. What pivot specifications meet all three requirements?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
site, period, metal, and value. The two lead readings are genuine replicates to average. What widening result matches that plan?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
A4:D4 holds headers and A5:D18 holds 14 data rows. An import supplies four replacement names and sets range = "A4:D18", skip = 4. The old header appears as data. What change removes it while retaining the replacement names and all 14 records?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
gs4_deauth() and successfully reads a worksheet. It now needs to replace the "Totals" worksheet. What access is required?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
sample, visit, analyte, value, and logged_at. Each sample has several visits, each analyte has one value per visit, and logging times differ by analyte. How should one row per sample-visit be created?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
dbConnect(duckdb::duckdb()). What connection choice makes storage persistent?Show answerHide answer
Save this lesson to see this answer.
Set 4: Plan complete workflows and explain failures10 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
NA because the measurements failed. An analyst needs both the average available reading and the number of failed measurements per logger. What pivot plan preserves the needed evidence?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
mass_1, mass_2, length_1, and length_2. A .value pivot keeps mass and length separate and creates visit. How many rows and measurement columns result?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
NA for sample J, test X, and no row for sample K, test X. A pivot uses values_fill = 0. What happens to those X cells?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
summarize(n = n()) |> collect() and returns 480,000,000. What does that local result contain?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
NULL, and site N has 5 and 7. A dbplyr query summarizes mean(x, na.rm = TRUE) by site and retains means greater than 5. What result is correct?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Apache Arrow
Authentication
gs4_auth() signs in an account, but that account still needs edit permission before it can write totals.B
Backend
C
Capture group
"([fm])([0-9]+)" extracts the letter, and the second extracts the following digits.Cell range
"2024!B3:E40" selects four columns on a named sheet, including its header when row 3 holds the names.collect()
collect() executes a lazy query and returns its result as a local R table, moving data across the engine-to-R boundary.collect() after a grouped summary transfers station averages instead of every original rainfall record.cols
cols argument selects the existing columns to reshape, leaving unselected columns to identify the resulting observations.cols = !station repeats the station name while the selected year measurements move into rows.Column specification
col_character() specification preserves a code like "00472" even if the sampled values look numeric.Columnar storage
Connection
dbConnect() and pass it to queries until the connection is closed with dbDisconnect().CSV
"Ruiz, Ana" retains its internal comma when the surrounding double quotes mark it as one field.D
Database
Dataset
open_dataset() can expose a folder of Parquet files while initially reading their structure and metadata.DBI
dbGetQuery() interface can request results through the backend for the database being used.dbplyr
summarize() can run in the database while the R script continues to use familiar dplyr syntax.Deauthorized mode
gs4_deauth() when the spreadsheet is readable by anyone with its link and only public reading is needed.Decimal mark
Delimiter
E
Excel date serial
G
Grouping mark
H
HAVING
HAVING is a SQL clause that filters groups using their summarized results, after aggregation has determined those results.Header
col_names = FALSE prevents its first measurement row from becoming column names.Hive-style directory
CheckoutYear=2021 supplies the year value for the records in that partition when opened.I
id_cols
id_cols argument selects the columns that together identify each output observation when a table is widened.visit with patient prevents tests from separate visits being combined into the same output row.Identifier
L
Lazy query
tbl(con, "rainfall") builds a query description; it does not download the complete rainfall table.List-column
Locale
M
Merged cell
Metadata
Missing-value code
na lets a temperature column contain numeric measurements and an actual NA.N
names_pattern
names_pattern argument uses a regular expression with capture groups to extract the required pieces of a compound heading.names_sep
names_sep argument gives a separator pattern used to split each selected heading into the pieces named by names_to.bike_am into mode and period, but also occurs inside an age band such as "18_34".names_to
names_to argument supplies the name or names of new columns that receive information extracted from the original headings.names_to = "year", headings such as 2023 become entries in a new column called year.names_transform
names_transform argument applies conversion functions to the new columns formed from headings during a longer pivot.as.integer gives numeric 1, 2, and 10 instead of text that sorts differently.NULL
NULL is SQL’s missing-value marker; missing entries are tested with IS NULL instead of ordinary equality.x = NULL fails to select missing measurements because that comparison evaluates as unknown.O
Observation
Observational unit
P
Parquet
parse_number()
parse_number() extracts the first number from text, recognizing locale-specific number marks while discarding surrounding text.Parsing
Partition pruning
CheckoutYear == 2021 can exclude other year folders before the engine reads their records.Partitioning
Persistent storage
pivot_longer()
pivot_longer() is a tidyr function that turns selected headings into values in a names column and stacks their measurements in another column.pivot_wider()
pivot_wider() is a tidyr function that turns values in a names column into headings and fills their cells from a measurement column.problems()
problems() is a readr function that reports failed parses with their locations, expected types, and actual source text.problems(depths) for an imported depths table helps distinguish an empty measurement from text that failed numeric conversion.R
RDS
read_rds().read_csv2()
read_csv2() is a readr function for semicolon-separated text with decimal commas, a common regional spreadsheet export format.read_delim(delim = ";") instead when a semicolon file writes measurements with decimal points.readxl
library(readxl) separately, even when library(tidyverse) has already loaded the main analysis packages.Remote execution
Reproducible import
S
show_query()
show_query() displays the SQL generated from a dbplyr pipeline without retrieving the query’s records into an R result.show_query() reveals whether an average and its filtering conditions are being expressed in the database.Snapshot
Source column
id = "file" setting makes it possible to check how many combined records came from each input.Spreadsheet ID
read_sheet() can take the ID between /d/ and /edit instead of the complete spreadsheet address.SQL
SELECT and WHERE can fetch the measurements for one year without returning the whole source table.Subquery
mutate() in the same pipeline.T
Text encoding
Tibble
read_csv() returns a tibble that can be inspected with glimpse() before any grouped analysis begins.tibble()
tibble() constructs a small table by defining named columns, with vectors supplying each column’s recorded values.tibble() call.Tidy data
height_cm and weight_kg columns can already form tidy data because they describe distinct variables.to_duckdb()
to_duckdb() exposes an Arrow object to DuckDB for SQL-backed querying without first copying the whole dataset into an R data frame.tribble()
tribble() constructs a small table in a row-oriented layout, using names prefixed with a tilde to declare its columns.tribble() shows each station beside its elevation on a single line of code.Type guessing
guess_max can reveal rare text, but the analyst must still decide whether a column contains identifiers.V
Value
rainfall_mm is one value; the other cells identify which station-year it describes.values_drop_na
values_drop_na argument controls whether a longer pivot removes output rows whose newly created value is missing.values_fill
values_fill argument supplies a value for output cells created from combinations that have no matching source row.values_fill = 0 for species absent at a site when the recording rule establishes zero.values_fn
values_fn argument supplies a function to combine source values that map to the same output cell during widening.values_fn = mean gives 5.6 from repeat measurements of 5.4 and 5.8 when an average is intended.values_to
values_to argument supplies the name of the new column that holds the cell contents stacked by an ordinary longer pivot.rainfall_mm keeps the measurement and its unit clear after the year columns are stacked.Variable
year is a variable even when its values were originally written as headings.W
Workbook
excel_sheets() lists the worksheets so the analysis can choose the one containing the required year’s data.Working directory
"data/samples.csv" works only when the working directory contains the intended data folder.Working memory
write_sheet()
write_sheet() writes a data frame into a Google worksheet, adding a missing target sheet or replacing an existing one.writexl
write_xlsx().#
.value
".value" name in a longer pivot makes one heading piece supply output column names for separate measurements..value keeps height and leaves in separate columns while week becomes an ordinary variable.- 1R and RStudio
- 2Data Visualization with ggplot2
- 3Transforming Data with dplyr
- 4Tidy Data and Data Import in R
- 5Strings and Factors in R
- 6Joins in R
- 7Exploratory Analysis in R
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.