Tidy Data and Data Import in R

Real data arrives in many shapes: CSV files with odd missing-value codes, semicolon files with decimal commas, Excel workbooks full of notes, shared Google Sheets, company databases and files too large to open. Learn to bring all of these into R and reshape them into tidy tables, where every variable is a column and every observation is a row. You will lengthen and widen tables with tidyr, import text files and spreadsheets with readr, readxl and googlesheets4, query databases with DBI and dbplyr, and analyze larger-than-memory data with Arrow and Parquet, checking each import as you go.

IntermediateLesson 4 of 7 in Data Analysis with R Course

What you will learn

  1. Recognize whether a dataset is tidy, and reshape untidy tables with tidyr's pivot_longer() and pivot_wider() so that every variable is a column and every observation is a row.
    • Recognize tidy data and spot untidy layouts
      State 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 variables
      Lengthen 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.
  2. 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 imported
      Read 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 problems
      Explain 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 formats
      Choose 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 data
      Read 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.
  3. 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 writexl
      List 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 googlesheets4
      Read 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.
  4. 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 DBI
      Explain 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 dbplyr
      Create 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 writes
      Read 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.
  5. 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 files
      Explain 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 dplyr
      Open 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.

Tidy Data and Data Import in R study guide

5 chapters

1

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

stationyearrainfall_mm
Alpha2022812
Alpha2024790
Beta2022640
Beta2023655
Beta2024701

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 cols for 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_sep when a separator divides the required pieces.
  • Capture groups in names_pattern fill names_to in order.
  • Use NA to discard an unwanted name piece.
  • Use ".value" when a name piece should name an output measurement column.
  • A .value pivot 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_from and values_from to 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.
2

Import 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_max improves 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 structurereadr function
Comma between fieldsread_csv()
Semicolon fields and decimal commasread_csv2()
Tab between fieldsread_tsv()
Another separator, such as a piperead_delim()
Fixed character positionsread_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
FormatMain strengthWhat to remember
CSVPlain text read by many programsTypes and factor level order are not stored
RDSPreserves the R objectIntended for use in R
ParquetTyped, compressed columns for many toolsRequires 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.
3

Get 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.
4

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

SystemExample backend
PostgreSQLRPostgres
MySQL or MariaDBRMariaDB
SQLiteRSQLite
DuckDBduckdb
BigQuerybigrquery
Systems with an ODBC driverodbc

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 reserve dbExecute() 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 operationMain SQL form
select(), rename(), mutate(), summarize()Expressions after SELECT; AS names results
filter() on source recordsWHERE
group_by() with a summaryGROUP 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.
5

Handle 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 and write_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

5 Walkthroughs

1

Reshape a table without losing its meaning

15 steps
Work from station-year observations through longer pivots, compound headings, and wider comparisons.
  1. 1
    IntroductionGive 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.

  2. 2
    ExplanationName 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, and rainfall_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.

  3. 3
    ChallengeDecide what should stay separate

    A table has one row per plant with plant, height_cm, and leaf_count. Must both measurements be stacked into one value column 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.

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

  5. 5
    ExampleLengthen 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.

  6. 6
    Key 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. Adding values_drop_na = TRUE leaves 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 = TRUE without deleting those observations from the table.

  7. 7
    ChallengePredict 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 adding values_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.

  8. 8
    ExampleSeparate mode from period

    The traffic headings bike_am, bike_pm, car_am, and car_pm each contain two variables. For a table traffic with a city identifier:

    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.

  9. 9
    TipKeep 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") with names_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.

  10. 10
    ExampleKeep height and leaves in different columns

    For a table plants with plant, height_1, height_2, leaves_1, and leaves_2, use:

    plants |>
      pivot_longer(
        cols = !plant,
        names_to = c(".value", "week"),
        names_sep = "_"
      )
    

    .value turns the first piece into output names height and leaves. The second supplies week. Three plants produce six plant-week rows, keeping centimeters and leaf counts in separate columns.

  11. 11
    ChallengeRead the pieces in order

    Columns are length_1, length_2, mass_1, and mass_2. A learner chooses names_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.

  12. 12
    ExampleBring 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`)
    

    station identifies 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.

  13. 13
    ExplanationResolve 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 = mean gives 5.6. The choice follows the meaning of the records.

  14. 14
    ChallengeChoose 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.

  15. 15
    RecapTrace 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.

2

Read, check, and combine text files

15 steps
Make missing codes, column types, regional conventions, and source tracking explicit in a reproducible import.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake the file’s conventions explicit
  2. 2
    ExampleRead the original text first
  3. 3
    ExampleRead and inspect the table
  4. 4
    ChallengeKeep the header out of the data
  5. 5
    ExplanationProtect meaning with column types
  6. 6
    ExampleTrace a failed numeric reading
  7. 7
    ChallengeExtract and scale a percentage
  8. 8
    ExampleMatch a decimal-comma file
  9. 9
    ExplanationSet conventions independently
  10. 10
    ChallengeChoose the parser from the raw line
  11. 11
    ExampleFind all intended files
  12. 12
    ExampleCheck each file’s contribution
  13. 13
    ConnectionSave for the next use
  14. 14
    ChallengePlan the complete monthly import
  15. 15
    RecapCheck structure and meaning together
3

Bring spreadsheet tables into R

11 steps
Select Excel cells and types, then read shared sheets with suitable access and repeatable snapshots.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSeparate the table from the spreadsheet
  2. 2
    ExampleList worksheets before choosing
  3. 3
    ExampleRead the rectangle with its headers
  4. 4
    Key InsightMake displayed meaning into data
  5. 5
    ChallengeCombine year sheets with their identities
  6. 6
    ExplanationChoose the access mode
  7. 7
    ExampleRead a public counts worksheet
  8. 8
    TipSave the input before it changes
  9. 9
    ChallengeWrite to the intended worksheet
  10. 10
    ChallengePreserve a repeatable multi-sheet analysis
  11. 11
    RecapRetain values, origins, and time
4

Build a query and collect its result

13 steps
Use DBI and dbplyr to keep reductions in the database, inspect SQL, and make the transfer to R explicit.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAsk the database for an answer
  2. 2
    ExampleCreate a temporary database
  3. 3
    ExampleRetrieve selected records
  4. 4
    ChallengeChoose the right side of the transfer
  5. 5
    ExampleBuild a lazy dplyr query
  6. 6
    ExampleExecute and collect the small result
  7. 7
    TipDo not infer size or order from a preview
  8. 8
    ChallengePlace the custom R step
  9. 9
    ExampleInspect the SQL without fetching
  10. 10
    Key InsightMissing values need a SQL test
  11. 11
    ChallengeDistinguish records from group results
  12. 12
    ChallengeOrder the workflow and close the connection
  13. 13
    RecapKnow which object is local
5

Query large files through Arrow

11 steps
Convert CSV to partitioned Parquet, run a lazy query, and handle memory and translation boundaries.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionRead less data to answer a large-data question
  2. 2
    ExplanationSeparate storage from execution
  3. 3
    ExampleOpen the CSV and protect an identifier
  4. 4
    ExampleWrite year-based Parquet partitions
  5. 5
    ChallengeChoose a manageable partition key
  6. 6
    ExampleBuild the monthly query
  7. 7
    ExampleCollect the monthly totals
  8. 8
    Key InsightA small answer still needs working space
  9. 9
    ConnectionChange engines deliberately
  10. 10
    ChallengeFix the query without collecting everything
  11. 11
    RecapMatch the storage layout to the query

Tidy Data and Data Import in R practice questions

40 Practice Questions in 4 sets

Set 1: Build and check import and query pipelines10 Practice Questions

Question 1 of 10

What feature of Parquet lets a reader avoid reading unrelated variables?
  1. Values are kept as plain text.
  2. Each column has a CSV header.
  3. Values are stored by column.
  4. Rows are read before projection.
Show answerHide answer
Answer: C
Parquet groups values by column, so a reader can request needed fields without reading every variable. That is distinct from partitioning, which divides records across files or folders. CSV also has column names, but its text layout does not supply Parquet’s column-based access to stored values.

Question 2 of 10

A workbook has a note above a table whose headers occupy C5:F5 and whose data end at row 24. What readxl range includes exactly the headers and data?
  1. range = "C6:F24"
  2. range = "C1:F24"
  3. range = "C5:F24"
  4. range = "C5:F5"
Show answerHide answer
Answer: C
The range must begin with the header row and extend through the last data row. 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

A table has 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?
  1. c(".value", "week")
  2. c("measure", "week")
  3. c("week", ".value")
  4. c(NA, "week")
Show answerHide answer
Answer: A
The first heading piece names a measurement, so .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

A database has values 2 and 14 for site U, and 10 and 12 for site V. Pipeline 1 filters values above 8 before averaging by site. Pipeline 2 averages by site and then filters means above 8. Which sites remain in each result?
  1. Pipeline 1: V only; pipeline 2: U and V.
  2. Pipeline 1: U and V; pipeline 2: U and V.
  3. Pipeline 1: V only; pipeline 2: V only.
  4. Pipeline 1: U and V; pipeline 2: V only.
Show answerHide answer
Answer: D
Filtering readings first leaves U with 14 and V with 10 and 12, so both resulting means exceed 8. Averaging first gives U a mean of 8 and V a mean of 11, so only V passes. Treating the two filters as interchangeable overlooks the low U reading removed before the first average.

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?
  1. It became zero; inspect the column mean in summary(df).
  2. It became NA; inspect its entry in problems(df).
  3. It stayed "trace"; inspect the guessed type in spec(df).
  4. Its row was removed; inspect the remaining row count.
Show answerHide answer
Answer: B
An entry that cannot be parsed into the requested numeric type becomes 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

Three compatible CSV files contain 86, 114, and 73 data rows. An import uses a path vector and id = "source". What result should its checks show?
  1. 270 rows, with source counts of 85, 113, and 72.
  2. 114 rows, with three source columns for the three files.
  3. 276 rows, with source counts of 87, 115, and 74.
  4. 273 rows, with source counts of 86, 114, and 73.
Show answerHide answer
Answer: D
Stacking adds the data rows from each file, so the total is 273 and the source column preserves the three contributions. The counts already describe data rows, so subtracting one header from each count would undercount. The id argument adds one source field, not one column per input file.

Question 7 of 10

A script reads a publicly viewable Google Sheet each morning. The same script later produces different historical results. What change makes the original analysis repeatable?
  1. Add gs4_auth() before every public-sheet reading.
  2. Increase n_max to include the entire current worksheet.
  3. Save and reuse a dated snapshot of each analysis input.
  4. Read the first visible worksheet by its numeric position.
Show answerHide answer
Answer: C
The live sheet can change between runs, so the code alone does not fix the input values. A saved snapshot preserves what the original analysis used. Authentication changes access, not data history; signing in again cannot recover earlier cell values that collaborators have since edited.

Question 8 of 10

What does tbl(con, "measurements") create when con is a database connection?
  1. A lazy reference to the stored table.
  2. A complete local copy of every stored row.
  3. A new empty table inside the database.
  4. A saved CSV containing the table preview.
Show answerHide answer
Answer: A
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

A query must retain records whose result is missing. What SQL condition expresses this?
  1. result = NULL
  2. result IS NULL
  3. result = "NA"
  4. result IS NOT NULL
Show answerHide answer
Answer: B
SQL represents missing entries as 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

An Arrow dataset exceeds local memory. A custom R function is needed only for the 200 grouped totals after filtering and summing, and Arrow supports those first steps. How should the pipeline be organized?
  1. Collect the dataset, then filter, summarize, and apply the R function.
  2. Apply the R function in Arrow, then filter, summarize, and collect.
  3. Convert to one local tibble, apply the function, then summarize.
  4. Filter and summarize in Arrow, collect, then apply the R function.
Show answerHide answer
Answer: D
The supported steps reduce the dataset to 200 totals before it enters local memory. The custom R function can then run on that small result. Collecting the original dataset defeats the memory plan, while placing the R-only function before collection asks Arrow to translate an expression it cannot execute.
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

A sensor table has columns sensor, 2021, and 2022; the year columns contain annual energy use in kJ. What reshaping makes year available as a variable?
  1. Transpose the table so each sensor becomes a separate column.
  2. Lengthen the year columns into year and energy_kj.
  3. Rename the headings to year_2021 and year_2022.
  4. Stack the sensor names and readings into one shared value column.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A table has four devices and five weekly reading columns. Exactly three of the reading cells are NA. After lengthening those five columns with values_drop_na = TRUE, how many rows remain?
  1. 20 rows
  2. 12 rows
  3. 7 rows
  4. 17 rows
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Headings are walk_day, walk_night, bus_day, and bus_night. What names_to and names_sep settings create columns called mode and period?
  1. names_to = c("mode", "period"), names_sep = "_"
  2. names_to = c("period", "mode"), names_sep = "_"
  3. names_to = c("mode", "period"), names_sep = "-"
  4. names_to = "mode", names_prefix = "period_"
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A completed inventory records only positive counts. All products were checked at each warehouse, and an absent warehouse-product row means none were present. What should fill absent combinations when widening by product?
  1. values_fn = mean
  2. values_drop_na = TRUE
  3. values_fill = 0
  4. names_prefix = "0"
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A comma file starts with two note lines, then a header, then data. It uses "missing" for unavailable measurements. How should the import handle these features?
  1. Use skip = 3 and na = c("", "NA", "missing").
  2. Use skip = 2 and na = c("", "NA", "missing").
  3. Use skip = 2 and col_names = FALSE.
  4. Use skip = 0 and comment = "missing".
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A product identifier is written as "00472" in a CSV. Which readr column type preserves its intended form?
  1. col_character()
  2. col_integer()
  3. col_double()
  4. col_logical()
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A file contains the header item;mass_kg and the row cable;6.25. What reader matches both the separator and the written number?
  1. read_csv2(path)
  2. read_csv(path)
  3. read_tsv(path)
  4. read_delim(path, delim = ";")
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A weekly table has headings wk1, wk2, and wk10. What settings create numeric values 1, 2, and 10 in a new week column?
  1. names_prefix = "wk", values_transform = list(value = as.integer)
  2. names_prefix = "week", names_transform = list(week = as.integer)
  3. names_prefix = "wk", names_transform = list(week = as.integer)
  4. names_to = "wk", values_to = "week"
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A DBI connection con is open. Which function returns a data frame from a SQL SELECT query?
  1. dbGetQuery(con, sql_text)
  2. dbExecute(con, sql_text)
  3. dbListTables(con)
  4. dbDisconnect(con)
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A 60 GB event dataset has 12 million device IDs and six years. Analysts repeatedly select one year and calculate totals using three of its 40 columns. What storage design best matches this workload?
  1. Parquet partitioned by device ID, retaining all 40 typed columns.
  2. Parquet partitioned by year, retaining all 40 typed columns.
  3. CSV partitioned by device ID, retaining the three frequently used columns.
  4. One CSV file sorted by year, retaining all 40 original columns.
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

A table has one row per parcel with columns 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?
  1. It already keeps the two measurement variables in separate columns.
  2. It needs lengthening because every numeric column must share a value field.
  3. It needs widening because each parcel must have a column of its own.
  4. It needs splitting because one observation cannot contain two measurements.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A table has 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?
  1. names_to = c("week", ".value"), names_pattern = "(.*)_([0-9]+)", names_transform = list(week = as.integer)
  2. names_to = c(".value", "week"), names_sep = "_", names_transform = list(week = as.integer)
  3. names_to = c(".value", "week"), names_pattern = "(.*)_([0-9]+)", names_transform = list(week = as.integer)
  4. names_to = c(".value", "week"), names_pattern = "(.*)_([0-9]+)", values_transform = list(week = as.integer)
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Rows are Q1, morning, lead, 2; Q1, morning, lead, 4; and Q1, morning, zinc, 8, in columns site, period, metal, and value. The two lead readings are genuine replicates to average. What widening result matches that plan?
  1. One Q1-morning row with lead 6 and zinc 8.
  2. One Q1-morning row with lead 3 and zinc 8.
  3. Two Q1-morning rows with lead 2 and 4, each with zinc 8.
  4. One Q1-morning row with lead 2 and zinc 8.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What value does readxl normally import from an Excel formula cell?
  1. The formula text as it was typed.
  2. A result recalculated during import.
  3. An NA for every formula cell.
  4. The last saved calculated result.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A pipe-delimited text file writes mass as "2.450,75". What number settings should accompany its pipe delimiter?
  1. locale(decimal_mark = ".", grouping_mark = ",")
  2. locale(decimal_mark = ",", grouping_mark = ",")
  3. locale(decimal_mark = ",", grouping_mark = ".")
  4. locale(encoding = "latin1")
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A table contains an ordered factor whose exact level order must survive saving and reloading in R. What format best fits this requirement?
  1. CSV
  2. RDS
  3. TSV
  4. Excel CSV
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

In a sheet, 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?
  1. Keep the supplied names; change the range to "A5:D18".
  2. Keep the supplied names; raise skip to 5 with the same range.
  3. Keep the supplied names; change the range to "A6:D18".
  4. Use col_names = TRUE; change the range to "A5:D18".
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A public-sheet script calls gs4_deauth() and successfully reads a worksheet. It now needs to replace the "Totals" worksheet. What access is required?
  1. Stay deauthorized; public viewing permission also permits replacement.
  2. Authenticate any account that can view the publicly accessible spreadsheet.
  3. Authenticate the original reader with permission to read the worksheet only.
  4. Authenticate an account with edit permission for that spreadsheet.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A table has 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?
  1. Use id_cols = sample, with analyte names and mean values.
  2. Use id_cols = c(sample, visit), with analyte names and values.
  3. Use all default identifiers, with analyte names and values.
  4. Use id_cols = c(sample, logged_at), with analyte names and values.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An analyst needs the same local DuckDB tables in a later R session. The connection currently uses dbConnect(duckdb::duckdb()). What connection choice makes storage persistent?
  1. Supply a file path with dbdir = "analysis.duckdb".
  2. Keep the default connection and disconnect it to save its tables.
  3. Read all tables into R before the current session ends.
  4. Give the connection a stable R name to reopen the database later.
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

A CSV field stores the name "Sato, Mei". How can the comma remain part of the name when the file is read?
  1. Enclose the complete field in R backticks.
  2. Replace the file header with the complete name.
  3. Put the name on its own unheaded data line.
  4. Enclose the complete field in double quotes.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Six loggers have four daily columns. Five cells are 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?
  1. Drop missing rows, then count the remaining rows as failed measurements.
  2. Fill missing readings with zero, then compute means and missing counts.
  3. Pivot logger identifiers too, then summarize every resulting value together.
  4. Keep missing rows, then compute missing counts and available-value means.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A table has four plots and columns 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?
  1. 16 rows and 1 measurement column.
  2. 8 rows and 2 measurement columns.
  3. 4 rows and 4 measurement columns.
  4. 8 rows and 4 measurement columns.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A lab table has a recorded 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?
  1. J receives zero; K stays missing because no row existed.
  2. Both receive zero because all missing values are replaced.
  3. J stays missing; K receives zero for the absent combination.
  4. Both stay missing because values_fill affects names only.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A CSV contains codes "007" and "019" and rates "32%" and "8%". The analysis needs unchanged codes and numeric proportions. What import and conversion plan meets both needs?
  1. Read codes as text; parse rates as numbers and divide by 100.
  2. Read codes as integers; parse rates as numbers and divide by 100.
  3. Read codes as text; parse rates as numbers with no rescaling.
  4. Read codes as doubles; convert rates with as.numeric() directly.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A tab-delimited UTF-8 file contains the label "café" and numbers with decimal points. The label becomes "café" after a Latin-1 locale was supplied. What setting should change?
  1. Use a semicolon reader while keeping Latin-1 encoding.
  2. Use UTF-8 encoding while keeping the tab reader.
  3. Use a decimal-comma locale while keeping Latin-1 encoding.
  4. Use comma fields while keeping decimal-point numbers.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A dataset query ends with summarize(n = n()) |> collect() and returns 480,000,000. What does that local result contain?
  1. A one-row count, not all 480 million source records.
  2. All 480 million source records plus their total count.
  3. A one-row preview of the first 480 million records.
  4. A table whose row count is still unknown until another collect.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A remote table has 80 million rows. A custom R scoring function is needed for the 300 rows meeting a supported database filter. The final output must be sorted by score. Where should collection occur?
  1. Before the remote filter, scoring function, and final local sort.
  2. After remote filtering, R scoring, and ordering by the new score.
  3. After the remote filter, before the R scoring function and local sort.
  4. After applying the R function remotely, before filtering and sorting.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

In a database, site M has readings 6 and 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?
  1. N alone remains, with mean 6.
  2. M remains with mean 3; N remains with mean 6.
  3. M and N remain, with means 6 and 12.
  4. M and N remain, each with mean 6.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An Arrow query filters one year, sorts all its events by time, groups by category, and sums amount before collection. There are six categories, and the report needs their totals sorted by category. The large time sort exhausts memory. What revised plan preserves the report and reduces sorting work?
  1. Filter the year, retain six source rows, group and sum, then collect.
  2. Filter the year, group and average, sort the categories, then collect.
  3. Filter the year, group and sum, sort the categories, then collect.
  4. Filter the year, collect the events, group and sum, then sort categories.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

77 Key Terms, each with its definition

A

Apache Arrow
Apache Arrow provides column-based data structures and a computing engine that the R arrow package makes available to R workflows.
Arrow can run dplyr operations on a file dataset before a reduced result becomes a local R tibble.
Authentication
Authentication identifies the Google account a script acts as, allowing access subject to that account’s spreadsheet permissions.
gs4_auth() signs in an account, but that account still needs edit permission before it can write totals.

B

Backend
A database backend is a package that implements DBI’s interface for a particular database system and its connection details.
RPostgres connects the common DBI functions to PostgreSQL, while duckdb connects them to DuckDB.

C

Capture group
A capture group is a parenthesized part of a regular expression that extracts a matching piece for a corresponding output column.
The first group in "([fm])([0-9]+)" extracts the letter, and the second extracts the following digits.
Cell range
A cell range identifies a rectangle of spreadsheet cells to import, allowing the table to be separated from surrounding content.
The 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.
Placing collect() after a grouped summary transfers station averages instead of every original rainfall record.
cols
The cols argument selects the existing columns to reshape, leaving unselected columns to identify the resulting observations.
Using cols = !station repeats the station name while the selected year measurements move into rows.
Column specification
A column specification states how an imported column should be interpreted, such as character labels or double-precision numbers.
An explicit col_character() specification preserves a code like "00472" even if the sampled values look numeric.
Columnar storage
Columnar storage organizes values by variable, allowing readers to access needed columns without reading all other fields.
Selecting rainfall and year avoids unrelated measurement columns when the file format supports columnar access.
Connection
A database connection is the active link through which R sends statements to a database and receives query results.
Store the object returned by dbConnect() and pass it to queries until the connection is closed with dbDisconnect().
CSV
A CSV file is a text file with comma-separated fields, usually a header row, and quotes around fields containing commas.
The field "Ruiz, Ana" retains its internal comma when the surrounding double quotes mark it as one field.

D

Database
A database stores organized tables and provides a system for retrieving and processing records without first loading them all into R.
A rainfall query can return only two selected columns for one year while the remaining records stay in storage.
Dataset
An Arrow dataset is a queryable view of files that can be treated as one table without loading all their records into R.
open_dataset() can expose a folder of Parquet files while initially reading their structure and metadata.
DBI
DBI is an R interface that defines shared functions for connecting to databases, managing tables, and retrieving query results.
The same dbGetQuery() interface can request results through the backend for the database being used.
dbplyr
dbplyr translates dplyr operations on database tables into SQL so the database can perform the requested calculations.
A grouped summarize() can run in the database while the R script continues to use familiar dplyr syntax.
Deauthorized mode
Deauthorized mode tells googlesheets4 to read publicly accessible sheets without requesting or supplying a login token.
Call gs4_deauth() when the spreadsheet is readable by anyone with its link and only public reading is needed.
Decimal mark
A decimal mark separates the whole-number and fractional parts of a written number, commonly using a point or a comma.
In the text "3,50", the comma is the decimal mark, so the number should become 3.5 in R output.
Delimiter
A delimiter is the character that separates fields in a text record, such as a comma, tab, semicolon, or vertical bar.
An imported header containing semicolons can show that a comma reader was used for the wrong delimiter.

E

Excel date serial
An Excel date serial is a day count used to store a calendar date, interpreted according to the workbook’s date system.
In the common 1900 date system, serial 45658 converts to January 1, 2025, using the matching date origin.

G

Grouping mark
A grouping mark divides digits into groups for readability without changing the magnitude or fractional boundary of a number.
In "1.234,5", the period groups thousands and the comma starts the fractional part, giving 1234.5.

H

HAVING
HAVING is a SQL clause that filters groups using their summarized results, after aggregation has determined those results.
Keeping stations with a mean above a threshold differs from first excluding individual readings below that threshold.
Header
A header is the opening record of a table that gives its column names, unless a file uses a different naming arrangement.
When a file has no header, col_names = FALSE prevents its first measurement row from becoming column names.
Hive-style directory
A Hive-style directory records a partition field and its value in a folder name, which can be reconstructed as a data column.
A folder named CheckoutYear=2021 supplies the year value for the records in that partition when opened.

I

id_cols
The id_cols argument selects the columns that together identify each output observation when a table is widened.
Including visit with patient prevents tests from separate visits being combined into the same output row.
Identifier
An identifier is a label used to distinguish an entity or record, even when its written form contains only numeric digits.
A product identifier such as "007" needs text storage because its leading zeros are part of the code.

L

Lazy query
A lazy query records operations to be executed later, allowing a database to process the complete request before returning results.
Adding a filter to tbl(con, "rainfall") builds a query description; it does not download the complete rainfall table.
List-column
A list-column is a column whose cells hold lists, allowing several values to occupy a destination that is not uniquely identified.
Two results for the same patient-test pair can create a list-column unless the repeats are handled deliberately.
Locale
A locale is a set of import conventions for interpreting numbers, text encoding, and related regional representations.
A decimal-comma locale can be paired with a pipe delimiter because number marks and field separators are separate settings.

M

Merged cell
A merged cell is a displayed spreadsheet block whose stored value occupies its top-left cell, leaving the other positions empty.
A site name shown across several merged rows can therefore appear only once after the values are imported.
Metadata
Metadata describes stored data, including column names, types, and files, allowing a dataset to be opened without reading every record.
Opening a Parquet directory inspects metadata before a later query requests the measurement values it needs.
Missing-value code
A missing-value code is a string used in a file to represent an unavailable value, which the reader must interpret as missing.
Adding "N/A" to na lets a temperature column contain numeric measurements and an actual NA.

N

names_pattern
The names_pattern argument uses a regular expression with capture groups to extract the required pieces of a compound heading.
A pattern can keep "18_34" together as an age band while extracting "female" from "female_18_34".
names_sep
The names_sep argument gives a separator pattern used to split each selected heading into the pieces named by names_to.
An underscore splits bike_am into mode and period, but also occurs inside an age band such as "18_34".
names_to
The names_to argument supplies the name or names of new columns that receive information extracted from the original headings.
With names_to = "year", headings such as 2023 become entries in a new column called year.
names_transform
The names_transform argument applies conversion functions to the new columns formed from headings during a longer pivot.
Converting week pieces with 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.
A filter using x = NULL fails to select missing measurements because that comparison evaluates as unknown.

O

Observation
An observation is a set of values recorded for the same unit at the same time, with its meaning determined by the analysis.
One station measured in two different years contributes two station-year observations to the rainfall table.
Observational unit
An observational unit is the entity and occasion described by one observation, which determines what identifies a row.
A table of stations describes one station per row, while a table of yearly rainfall records describes one station in one year.

P

Parquet
Parquet is an open binary format for tabular files that preserves column types and stores compressed data by column.
A query needing only three fields can avoid reading unrelated variables from a much wider Parquet dataset.
parse_number()
parse_number() extracts the first number from text, recognizing locale-specific number marks while discarding surrounding text.
Parsing "45%" gives 45; converting it to a proportion still requires dividing the extracted value by 100.
Parsing
Parsing interprets source text as values of a requested type, such as converting the text "2.5" into a numeric measurement.
Trying to parse "deep" as a double produces a missing result and a warning that should be investigated.
Partition pruning
Partition pruning skips partitions that cannot satisfy a query’s filter, reducing the files that the engine needs to read.
Filtering CheckoutYear == 2021 can exclude other year folders before the engine reads their records.
Partitioning
Partitioning splits a dataset across files or folders according to a variable’s values, allowing matching filters to skip files.
Year-based partitions help a query limited to one year avoid reading the folders for all the other years.
Persistent storage
Persistent storage keeps a database’s data in a file or service after the current R session or connection has ended.
A DuckDB connection with a database file path can reopen saved tables in another session, unlike a temporary database.
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.
Lengthening three year columns in a two-station table gives six rows before missing values are removed.
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.
Widening patient test records makes one row per patient with glucose and sodium results side by side.
problems()
problems() is a readr function that reports failed parses with their locations, expected types, and actual source text.
Inspecting problems(depths) for an imported depths table helps distinguish an empty measurement from text that failed numeric conversion.

R

RDS
RDS is an R-specific serialization format that saves one R object with its types and attributes for later restoration.
Saving an ordered factor in RDS preserves its level order when the object is loaded again with read_rds().
read_csv2()
read_csv2() is a readr function for semicolon-separated text with decimal commas, a common regional spreadsheet export format.
Use read_delim(delim = ";") instead when a semicolon file writes measurements with decimal points.
readxl
readxl is an R package for reading values from Excel workbooks without needing an installed copy of Excel.
Load library(readxl) separately, even when library(tidyverse) has already loaded the main analysis packages.
Remote execution
Remote execution means that a database engine performs the requested operations while the stored records remain outside local R tables.
Filtering remotely reduces the rows transferred, but a custom R function must run after a suitable result is collected.
Reproducible import
A reproducible import records the steps that turn preserved raw inputs into processed tables so the same process can run again.
A script reads unchanged raw files and writes results to another folder, keeping the original inputs available.

S

show_query()
show_query() displays the SQL generated from a dbplyr pipeline without retrieving the query’s records into an R result.
Inspecting show_query() reveals whether an average and its filtering conditions are being expressed in the database.
Snapshot
A snapshot is a saved copy of the data read at a particular time, preserving a fixed input from a source that may change.
A dated CSV of imported volunteer counts lets a later analysis use the same records despite edits to the live sheet.
Source column
A source column records where each imported row came from, preserving file-level information when several inputs are stacked.
When monthly files are read together, the id = "file" setting makes it possible to check how many combined records came from each input.
Spreadsheet ID
A spreadsheet ID is the identifying string in a Google Sheets URL that lets the API locate that spreadsheet independently of its title.
read_sheet() can take the ID between /d/ and /edit instead of the complete spreadsheet address.
SQL
SQL is the Structured Query Language, used to express which records and columns a database should return or calculate.
A query with SELECT and WHERE can fetch the measurements for one year without returning the whole source table.
Subquery
A subquery is a query nested inside another query, allowing a later operation to use a result produced at an earlier level.
dbplyr may use a subquery when filtering on a new column created by mutate() in the same pipeline.

T

Text encoding
A text encoding defines how bytes represent characters, which determines whether accents and other written symbols display correctly.
UTF-8 bytes decoded as Latin-1 can show "é" where the original label contained the accented letter "é".
Tibble
A tibble is a tidyverse form of data frame that stores named columns and displays a compact view of their values and types.
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.
A two-station lookup can pair a station-name vector with elevations in meters using one tibble() call.
Tidy data
Tidy data is organized so that each variable has a column, each observation has a row, and each individual value has a cell.
Separate 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.
Use the handoff when DuckDB supports a needed operation that the current Arrow dataset query cannot translate.
tribble()
tribble() constructs a small table in a row-oriented layout, using names prefixed with a tilde to declare its columns.
A short lookup written with tribble() shows each station beside its elevation on a single line of code.
Type guessing
Type guessing infers a column type from sampled values, so unusual entries or misleading numeric-looking labels can defeat it.
A larger guess_max can reveal rare text, but the analyst must still decide whether a column contains identifiers.

V

Value
A value is one recorded entry for a variable in an observation, such as the rainfall measured at a particular station in a year.
The entry 790 in rainfall_mm is one value; the other cells identify which station-year it describes.
values_drop_na
The values_drop_na argument controls whether a longer pivot removes output rows whose newly created value is missing.
Keep the missing logger readings when the analysis must count failed measurements for each device.
values_fill
The values_fill argument supplies a value for output cells created from combinations that have no matching source row.
A completed survey can use values_fill = 0 for species absent at a site when the recording rule establishes zero.
values_fn
The values_fn argument supplies a function to combine source values that map to the same output cell during widening.
Using values_fn = mean gives 5.6 from repeat measurements of 5.4 and 5.8 when an average is intended.
values_to
The values_to argument supplies the name of the new column that holds the cell contents stacked by an ordinary longer pivot.
Naming the column rainfall_mm keeps the measurement and its unit clear after the year columns are stacked.
Variable
A variable is a quantity, quality, or property recorded across observations, such as a station name or an annual rainfall measurement.
In a rainfall table, year is a variable even when its values were originally written as headings.

W

Workbook
A workbook is an Excel file that can contain multiple worksheets, each potentially holding notes, tables, or other content.
excel_sheets() lists the worksheets so the analysis can choose the one containing the required year’s data.
Working directory
The working directory is the folder R uses as the starting point when a file path does not give a complete location.
The path "data/samples.csv" works only when the working directory contains the intended data folder.
Working memory
Working memory is memory used by intermediate query operations, in addition to the space needed for the final collected table.
A large sort may require substantial working memory even when a later summary returns only a few totals.
write_sheet()
write_sheet() writes a data frame into a Google worksheet, adding a missing target sheet or replacing an existing one.
Writing to "Totals" clears the old target contents and formatting, so choose the destination deliberately.
writexl
writexl is an R package that writes data frames to Excel files, with a named list creating separate named worksheets.
A named list of rainfall and station tables can become a two-worksheet workbook through write_xlsx().

#

.value
The special ".value" name in a longer pivot makes one heading piece supply output column names for separate measurements.
When headings combine a measurement name and a week, .value keeps height and leaves in separate columns while week becomes an ordinary variable.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

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

Get Started