Exploratory Analysis in R: Reporting with Quarto

Learn to explore a dataset in R and report what you find in documents that rebuild themselves from code. Ask focused questions, describe how single variables vary, deal with unusual and missing values, and look for covariation between categorical and numerical variables. Then write Quarto documents that combine prose, code and results, render them as HTML, PDF or Word reports, slides and dashboards, keep the work reproducible with parameters and caching, and communicate findings clearly and honestly to the people who need them.

IntermediateLesson 7 of 7 in Data Analysis with R Course

What you will learn

  1. Use questions to guide an exploratory data analysis, describe how single variables vary, and decide what to do with unusual and missing values.
    • Plan an exploratory analysis around questions
      Treat exploration as a cycle of questions and answers, take a first structured look at a dataset, and turn vague curiosity into questions you can answer with plots and summaries.
    • Describe how a single variable varies
      Choose the right plot for one categorical or numerical variable, read typical values, spread and clusters from it, and back up what you see with summary statistics.
    • Find and handle unusual and missing values
      Spot outliers that are hard to see in large datasets, decide whether to keep, correct or replace them, and investigate what missing values can tell you.
  2. Choose plots and summaries that reveal covariation between categorical and numerical variables, and judge whether a pattern is real, how strong it is and what else might explain it.
    • Compare a numerical variable across categories
      Compare distributions between groups with boxplots, density-scaled frequency polygons and reordered categories, and recognize when a third variable distorts the comparison.
    • Explore two categorical variables
      Count every combination of two categorical variables, show the counts as a count plot or heatmap, and compare proportions within groups rather than raw counts.
    • Explore two numerical variables and judge patterns
      Plot two numerical variables without overplotting, describe the direction, form and strength of the relationship, and check whether subgroups or other variables change the picture.
  3. Combine prose, R code and results in a Quarto document, control what each code chunk shows, and add figures, tables, cross-references and citations.
    • Build and render a Quarto document
      Recognize the three parts of a Quarto file, write Markdown text, and render the document while understanding that rendering runs all code in a fresh R session.
    • Control code chunks with options and inline code
      Use chunk labels and options to decide what code and output appear, set defaults for the whole document, and place computed numbers directly in the text.
    • Add figures, tables, cross-references and citations
      Size and caption plots, present summary tables, refer to figures and tables by number, and cite sources from a bibliography file.
  4. Render one analysis to the format that suits its readers: HTML, PDF or Word documents, slide presentations, or a dashboard of key results.
    • Render documents to HTML, PDF and Word
      Set the output format and its options in the YAML header, render to several formats, and choose the format that fits how readers will use the report.
    • Present results as slides
      Turn an analysis into a slide presentation with revealjs, PowerPoint or Beamer, structure the slides with headings, and keep each slide focused on one message.
    • Build a dashboard
      Lay out key results as a Quarto dashboard with pages, rows, columns, cards and value boxes, and know what a static dashboard can and cannot do.
  5. Organize files, code and software so that anyone can re-render the analysis and get the same results, and reuse one report for many variants with parameters and caching.
    • Make a report that anyone can re-render
      Organize the project so every result comes from code and raw data, control randomness, record software versions, and test the report by rendering it from a clean start.
    • Reuse reports with parameters and save time with caching
      Declare parameters to render one report for different groups or periods, render the variants from the command line or from R, and speed up slow renders with caching and freezing.
  6. Turn an exploration into a clear report for its readers, with explanatory figures and plain-language findings, and state honestly what exploratory results can and cannot show.
    • Plan and write a report for its readers
      Choose what to include for a given audience, structure the report around the answer to its question, and make figures, numbers and text easy to understand.
    • Report exploratory findings honestly
      Word conclusions so they match what exploratory data can support, report the data's limits and the choices you made, and avoid presentations that mislead.

Exploratory Analysis in R study guide

6 chapters

1

Explore a dataset by asking questions

Exploration turns a table into questions you can investigate. Start by checking what each row and variable means, then use simple plots and summaries to understand variation. Unusual and missing values can change both the analysis and the questions worth asking. Keep a record of your decisions so a later report can explain how the evidence was prepared and why a particular comparison matters.

1.1 Plan an exploratory analysis around questions

A useful exploration starts with something you want to understand. You ask a question, inspect the data, make a plot or summary, and let the answer guide your next question. This cycle is exploratory data analysis, or EDA. It helps you discover both patterns and problems before preparing a report.

Know what one row represents

A variable is something measured, such as body mass or species. A value is one recorded result. An observation collects measurements of the same object at the same time. In tidy data, each observation occupies one row and each variable one column. Knowing what a row represents matters: a table of individual birds answers different questions from a table of species averages.

Load the packages and inspect the data before building detailed plots:

library(tidyverse)
library(palmerpenguins)
glimpse(penguins)
penguins |> count(species)
penguins |>
  summarize(across(everything(), function(x) sum(is.na(x))))

glimpse() shows 344 rows and eight columns, including species, island, four measurements, sex, and year. Species counts are 152 Adelie, 68 Chinstrap, and 124 Gentoo. Each measurement column has two missing values; sex has 11. These checks tell you the group sizes and how much information each comparison can use.

Check the meaning of the values

Inspect units, ranges, category labels, and duplicated rows. Body mass ranges from 2,700 to 6,300 g; flipper length ranges from 172 to 231 mm. A negative length or a missing-value code such as -99 needs investigation before a summary treats it as a measurement. A duplicated row also needs context: repeated measurements and accidental copies have different meanings.

Find out who collected the data, where, and when. These penguins were measured on three islands near Palmer Station, Antarctica, in 2007–2009. That setting belongs beside any later interpretation of the patterns.

Turn curiosity into a comparison

A variation question concerns one variable: "How spread out are body masses?" A covariation question concerns variables together: "How does body mass differ by species?" A focused question names the measurement, the comparison, and any relevant subgroup.

For example, begin with a histogram of body mass. Its wide spread suggests comparing species. The species medians are 3,700 g for Adelie and Chinstrap and 5,000 g for Gentoo. A further question is whether sex explains some spread within a species. Mean body mass among Gentoo penguins is about 4,680 g for females and 5,485 g for males. One broad distribution has led to two more precise comparisons.

Record the question, code, finding, and next question together as you work. Keep useful dead ends too: a note explaining why a plot did not answer the question saves repeated work. A Quarto notebook keeps this record beside the code and its results.

Searching many patterns in one dataset can uncover chance patterns. An exploratory finding therefore supplies a hypothesis for further investigation. Treating the first striking plot as a confirmed explanation skips the work of checking it on new data or with an appropriate formal method.

Key Takeaways

  • EDA cycles through questions, plots or transformations, and new questions.
  • Check row meaning, types, counts, units, ranges, and missing values first.
  • Variation concerns one variable; covariation concerns variables together.
  • A focused question names a measurement and comparison.
  • Keep an analysis record, including useful dead ends.

1.2 Describe how a single variable varies

A distribution describes which values a variable takes and how often they occur. Read it as a pattern: where values gather, how far they spread, and whether gaps or unusual tails need investigation. A single average cannot show all of this.

Match the plot to the variable

A categorical variable records a group or label. A bar chart counts observations in each category:

ggplot(penguins, aes(x = species)) + geom_bar()

A numerical variable records a quantity. For body mass, group nearby values into bins with a histogram:

ggplot(penguins, aes(x = body_mass_g)) +
  geom_histogram(binwidth = 200)

Each bar counts birds in a 200 g interval. Using geom_bar() on body mass instead would count every distinct recorded mass separately. It would not group nearby masses into intervals.

Change the binwidth before trusting the shape

Binwidth is measured in the variable's units. Try 100, 200, and 500 g. Narrow bins show fine detail but can make random fluctuations look prominent. Wide bins smooth over detail and can hide separate clusters. Without a chosen binwidth, ggplot2 uses 30 bins and suggests choosing a better value.

Ask which values are common or rare, whether there are sharp peaks or gaps, and what could explain them. A cluster of similar masses may represent a subgroup. Add facet_wrap(~species) to inspect a histogram per species. The combined distribution includes 342 birds with recorded mass and mixes three species with different typical masses.

Describe center and spread together

The median marks the middle of the ordered values; the mean uses every value in an arithmetic average. The interquartile range, or IQR, is the third quartile minus the first quartile. It describes the width of the middle half of the data. The standard deviation describes spread around the mean.

penguins |>
  summarize(
    measured = sum(!is.na(body_mass_g)),
    median_g = median(body_mass_g, na.rm = TRUE),
    iqr_g = IQR(body_mass_g, na.rm = TRUE),
    mean_g = mean(body_mass_g, na.rm = TRUE),
    sd_g = sd(body_mass_g, na.rm = TRUE)
  )

The median is 4,050 g, the IQR 1,200 g, the mean about 4,202 g, and the standard deviation about 802 g. The first and third quartiles are 3,550 and 4,750 g. Leaving out na.rm = TRUE makes these summaries return NA because two masses are missing. Removing missing values from a calculation does not change them into measured values.

The mean sits above the median here, consistent with more weight in the upper part of the distribution. Inspect the histogram to judge the shape; the ordering of mean and median alone cannot establish it. For skewed data or data with extreme values, median and IQR give more resistant summaries than mean and standard deviation.

Subgroups also differ in spread. The middle half of Gentoo masses runs from 4,700 to 5,500 g; the middle half of Adelie masses runs from 3,350 to 4,000 g. These intervals help explain what a species comparison adds beyond the overall average.

Key Takeaways

  • Use bar charts for categories and histograms for numerical distributions.
  • Check several binwidths; bins have the same units as the measurement.
  • Read clusters, gaps, and tails as well as typical values.
  • Report center with spread and the number of measured observations.
  • Median and IQR resist extreme values more than mean and standard deviation.
  • Use na.rm = TRUE when calculating a summary from recorded values.

1.3 Find and handle unusual and missing values

An unusual value deserves attention before a decision. It may be a genuine extreme measurement, a recording error, or evidence of a subgroup you have not recognized. Missing values deserve similar care because their pattern can tell you something about the observations.

Inspect the unusual observations

In a large histogram, a bar containing only a few records can be almost invisible. Zoom the displayed count axis while keeping all the data available to the plot:

ggplot(diamonds, aes(x = y)) +
  geom_histogram(binwidth = 0.5) +
  coord_cartesian(ylim = c(0, 50))

Here y is diamond width in millimeters. The unusual widths are near 0, 30, and 60 mm. Inspect the actual rows:

diamonds |> filter(y < 3 | y > 20)

This finds nine of 53,940 records: seven zero widths and widths of 31.8 and 58.9 mm. The remaining widths range from 3.68 to 10.54 mm. Zero width is impossible; the large values also need checking against the original records and other measurements.

coord_cartesian() changes the viewing window. Scale limits such as xlim() and ylim() remove out-of-range values before statistical summaries are calculated. That can change a histogram or boxplot, so use coordinate zooming when the aim is to inspect the same calculation more closely.

Preserve the useful measurements

Once a measurement is judged wrong, replace that measurement with NA in a cleaned copy:

diamonds_clean <- diamonds |>
  mutate(y = if_else(y < 3 | y > 20, NA_real_, y))

The row's price, cut, and other measurements remain available. Filtering the entire row would discard them too. Keep the raw data unchanged and record why the rule identifies suspect widths. Compare conclusions with and without the flagged measurements. A large change needs an explanation, not a quiet deletion to make a plot tidier.

Ask where values are missing

NA means that a value is unavailable; it is not a measured zero. Numerical summaries such as mean() return NA unless told to omit missing values. A plot cannot place a missing numerical coordinate, so ggplot2 leaves that observation out and normally warns. A discrete scale can show missingness as an NA category: a bar chart of penguin sex includes the 11 birds with no recorded sex.

penguins |>
  mutate(sex_missing = is.na(sex)) |>
  count(species, sex_missing)

This separates recorded and missing sex within each species. Missing sex occurs for six Adelie and five Gentoo birds. Comparing missingness by island or year may reveal where the recording process differs.

Name the variables that an analysis actually needs when dropping missing observations. drop_na(body_mass_g) preserves birds with known mass even if sex is missing. An unrestricted drop_na() retains only 333 complete rows and discards nine fully measured birds whose sex is unknown. Report how many observations each analysis uses, especially when comparing results built from different sets of rows.

Key Takeaways

  • Investigate outliers before deciding whether they are errors.
  • Coordinate zooming preserves the data used to compute a plot.
  • Replace a wrong measurement with NA while preserving other useful values.
  • Keep raw data unchanged and record the cleaning rule.
  • Investigate patterns of missingness; missing is different from zero.
  • Drop missing values only for variables the analysis needs.
2

Explore how variables vary together

Relationships need a display that fits the variables. Compare numerical distributions across groups, count categorical combinations with the right denominator, and inspect numerical pairs for trends and hidden structure. Group size, overlapping points, and third variables can alter the apparent pattern. The aim is to describe the evidence clearly before deciding what might explain it.

2.1 Compare a numerical variable across categories

A numerical variable can vary differently across groups. Compare the distributions, including their center, spread, and shape. Group sizes and other variables can change the story a simple comparison seems to tell.

Read a boxplot
ggplot(penguins, aes(x = species, y = body_mass_g)) +
  geom_boxplot()

The line inside each box marks the median. The box covers the middle half of the values, from the first to the third quartile. Its length is the IQR. Whiskers extend to the most extreme observations within 1.5 IQR of the box edges; values farther away appear as separate points. Those points are candidates for investigation, not an automatic deletion list.

For all measured penguins together, the quartiles are 3,550 and 4,750 g and the IQR is 1,200 g. The lower and upper fences are 1,750 and 6,550 g. All recorded masses fall inside them. A whisker ends at an observed value within its fence, so its endpoint need not equal the calculated fence.

Species medians are 3,700 g for Adelie and Chinstrap and 5,000 g for Gentoo. The Gentoo box runs from 4,700 to 5,500 g; the Adelie box runs from 3,350 to 4,000 g. That separation is large compared with their middle-half spreads in this sample. Box overlap alone is not a formal test of a population difference.

Compare shapes when group sizes differ

A frequency polygon shows binned counts as a line. Count curves for 152 Adelie and 68 Chinstrap birds partly reflect how many birds were sampled. To compare distribution shapes, scale each group to a density whose total area is one:

ggplot(penguins, aes(
  x = body_mass_g, color = species,
  y = after_stat(density)
)) + geom_freqpoly(binwidth = 200)

The vertical scale now describes density, not bird counts. Density curves, violin plots, and faceted histograms can reveal features a boxplot hides, such as two peaks. A boxplot also hides sample size unless it is added separately; varwidth = TRUE makes box widths proportional to the square roots of group sizes.

Order groups to help the reader

An unordered category can be sorted by a numerical summary:

penguins |>
  drop_na(body_mass_g) |>
  ggplot(aes(
    x = body_mass_g,
    y = fct_reorder(species, body_mass_g, median)
  )) + geom_boxplot()

Placing categories on the vertical axis gives long labels more room. Preserve a meaningful existing order, such as diamond cut from Fair to Ideal, instead of sorting it away.

Check a third variable

Ideal-cut diamonds have a median price of 1,810 US dollars, below the Fair-cut median of 3,282 US dollars. But the typical sizes differ: median carat is 0.54 for Ideal and 1.00 for Fair. The comparison mixes cut with size, and larger diamonds cost more. Examine comparable size groups before attributing the price pattern to cut. The boxplots describe the observed groups; they do not isolate what changing cut would do.

Key Takeaways

  • A boxplot shows median, IQR, whiskers, and possible outliers.
  • Whiskers end at observations, not necessarily at the 1.5-IQR fences.
  • Use density scaling to compare shapes across unequal group sizes.
  • Use another plot when peaks or detailed shape matter.
  • Preserve natural category order and check third variables.

2.2 Explore two categorical variables

Two categorical variables describe combinations of groups. Begin by counting each combination, then decide which total makes a useful denominator. A large count can mean that a combination is common or simply that its parent group is large.

Count combinations and show zeros
penguins |> count(island, species)

The observed counts are 44 Biscoe–Adelie, 124 Biscoe–Gentoo, 56 Dream–Adelie, 68 Dream–Chinstrap, and 52 Torgersen–Adelie. The table has five rows because count() lists observed combinations. It does not add a row for Gentoo on Dream.

To show every combination explicitly:

penguins |>
  count(island, species) |>
  complete(island, species, fill = list(n = 0))

Three islands and three species give nine combinations. Filling missing combinations with zero says there were no such observations in this dataset. That differs from a missing measurement whose value is unknown.

Choose a display for the counts

geom_count() plots a circle at each combination, with its size showing the count. A heatmap puts the count into tile color:

penguins |>
  count(island, species) |>
  complete(island, species, fill = list(n = 0)) |>
  ggplot(aes(x = island, y = species, fill = n)) +
  geom_tile()

Explicit zeros make absence easier to distinguish from combinations omitted during table preparation. With many categories, a heatmap can be easier to scan than a long table. The diamonds data, for example, have 35 color–cut combinations.

Choose the denominator from the question

"Which species were measured on each island?" requires proportions within islands:

penguins |>
  count(island, species) |>
  group_by(island) |>
  mutate(prop = n / sum(n))

Biscoe contains 168 sampled penguins: 44 Adelie and 124 Gentoo. Its proportions are 26.2% Adelie and 73.8% Gentoo. Dream is 45.2% Adelie and 54.8% Chinstrap. Torgersen is entirely Adelie in these observations.

"Where were the Adelie penguins measured?" uses the species total instead. Of 152 Adelie birds, 44 were on Biscoe, 56 on Dream, and 52 on Torgersen: 28.9%, 36.8%, and 34.2%. The Biscoe–Adelie count is still 44, but the denominator has changed from 168 to 152. Write the question before choosing group_by().

A proportional bar chart uses geom_bar(aes(fill = species), position = "fill"), with island mapped to the horizontal axis. Every island bar has height one. position = "dodge" instead places count bars side by side; it answers a different comparison.

Describe the sampled setting. "Gentoo penguins were measured only on Biscoe in this dataset" stays within the observations. A claim about every island where the species lives would require broader evidence. Likewise, raw counts of diamond colors are affected by the much larger number of Ideal than Fair diamonds; compare within-cut proportions when the question concerns color composition.

Key Takeaways

  • Count combinations first and add explicit zeros with complete() when useful.
  • Use circle size or tile color to display combination counts.
  • The question determines the denominator and grouping variable.
  • Proportional bars compare composition; dodged bars compare counts.
  • Describe sampled combinations without extending them to all settings.

2.3 Explore two numerical variables and judge patterns

For two numerical variables, start with a scatterplot. Each point represents one observation, with a horizontal and vertical position. Look for the direction, form, and strength of the relationship before reducing it to a number.

Read the pattern and its correlation
ggplot(penguins, aes(
  x = flipper_length_mm, y = body_mass_g
)) + geom_point()

Longer flippers tend to occur with greater body mass: the direction is positive. The form is roughly linear. Strength concerns how tightly the points follow that form. A curve, separate clusters, or isolated points require a fuller description than "positive."

The correlation coefficient, r, measures linear direction and strength. It ranges from −1 for a perfect downward line to 1 for a perfect upward line. A value near zero indicates little linear relationship, even when a strong curve is present.

cor(penguins$flipper_length_mm, penguins$body_mass_g,
    use = "complete.obs")

The result is about 0.87 from 342 complete measurement pairs. Always inspect the plot alongside r. Adding geom_smooth() supplies a visual trend guide, not confirmation of an explanation.

Reveal observations hidden by overlap

A scatterplot of 53,940 diamonds has many points at the same or nearby positions. This overplotting hides density. Small transparent points, such as geom_point(alpha = 0.01), help reveal crowded regions. geom_bin2d() groups points into rectangular cells and colors them by count; geom_hex() does the same with hexagons and needs the hexbin package.

Another approach groups one numerical variable and compares the other within bins:

ggplot(diamonds, aes(x = carat, y = price)) +
  geom_boxplot(aes(group = cut_width(carat, 0.1)))

cut_width() creates equal-width intervals, which may contain very different numbers of diamonds. cut_number(carat, 20) instead aims for 20 groups with roughly equal counts. These choices emphasize different features: equal intervals preserve the measurement scale, while equal counts distribute observations more evenly. Variable box widths can indicate the square roots of bin counts.

Look inside the combined pattern

Across all penguins, bill length and depth have a weak negative correlation, about −0.24. Yet within species, the correlations are positive: about 0.39 for Adelie, 0.65 for Chinstrap, and 0.64 for Gentoo. Color the scatterplot by species to reveal this structure.

Gentoo birds tend to have long, shallow bills relative to other species. Differences between species shape the combined downward pattern even though the relationship within each species points upward. A combined relationship that changes or reverses within subgroups is known as Simpson's paradox.

Ask whether the pattern survives subgroup checks, what other variables could explain it, and whether chance could account for it. Covariation can help predict one measurement from another, but observational association alone cannot establish which variable causes a change. Report the combined and subgroup patterns when their difference changes the interpretation.

Key Takeaways

  • Describe scatterplots by direction, form, and strength.
  • Correlation measures linear relationships; inspect curves and clusters separately.
  • Use transparency or two-dimensional bins to address overplotting.
  • Equal-width and roughly equal-count bins answer different needs.
  • Check subgroups for changes or reversals in the combined pattern.
  • Association can support prediction without establishing causation.
3

Write reproducible reports in Quarto documents

A reproducible document keeps explanation close to the code that supports it. Build a Quarto source with Markdown, executable chunks, and output settings, then render it in a fresh R session. Control which code and results readers see, connect computed numbers to prose, and give figures and tables useful captions and numbered references. These choices make the report easier to maintain as the analysis changes.

3.1 Build and render a Quarto document

Quarto combines written explanation, executable code, and computed results in a plain-text document. Rendering turns that source into a report. Because the results come from code, changes to the analysis can flow into the published text, figures, and tables.

Build the three parts

A Quarto document uses the .qmd extension. Its optional YAML header sets metadata and options between two lines containing ---. Markdown supplies the surrounding text. Executable code chunks begin with three backticks followed by {r} and end with three backticks.

---
title: "Penguin measurements"
format: html
---

## Data

```{r}
#| label: setup
#| message: false
library(tidyverse)
library(palmerpenguins)
```

The measurements cover penguins from three islands.

```{r}
penguins |> count(species)
```

This source produces an HTML report with a heading, a sentence, code, and the species counts. Loading palmerpenguins selects the dataset whose columns include body_mass_g and flipper_length_mm. Install packages once in the console before rendering; package installation is not an analysis step to repeat in every report.

Write readable Markdown

Use #, ##, and ### for heading levels, *italic* and **bold** for emphasis, and a line beginning with - for a list. A link has the form [label](https://example.org). An image uses ![caption](figure.png). Backticks mark literal code such as count(). Leave blank lines between paragraphs and before headings and lists.

RStudio's source editor shows this syntax. Its visual editor displays formatted content and provides menus for elements such as tables and citations. Both edit the same plain-text document. Insert a chunk with Cmd/Ctrl + Alt + I and run one chunk with Cmd/Ctrl + Shift + Enter.

Render from a fresh session

Use the Render button or Cmd/Ctrl + Shift + K. From a terminal, run:

quarto render report.qmd

From R, use quarto::quarto_render("report.qmd"). quarto preview report.qmd renders a preview that updates when the source is saved.

For R documents, knitr executes the chunks and makes Markdown containing the results. Pandoc converts that Markdown to the requested output. Quarto also supports existing R Markdown documents and uses knitr to run their R code.

The render uses a fresh R session. An object created only in the console will be unavailable, even if a chunk ran successfully while you were experimenting. Put package loading, imports, and every object creation in the document, in the order needed. If a plot refers to penguins_clean, an earlier chunk must create it.

By default, a document's folder is its working directory during rendering. A relative path such as data/penguins.csv is interpreted from there. Remove interactive viewing calls such as View() from report chunks. Save executable content as .qmd: Quarto can render .md as Markdown, but does not execute its R chunks.

Key Takeaways

  • A Quarto source combines YAML options, Markdown prose, and executable chunks.
  • knitr executes R code; Pandoc converts the resulting Markdown.
  • A render must create its own objects and load its own packages.
  • Relative paths normally start from the document folder.
  • Use .qmd for executable Quarto documents.

3.2 Control code chunks with options and inline code

Chunk options separate computation from presentation. A report may need code to run even when readers never see it. Inline code then lets the surrounding sentences use the same computed values as the figures and tables.

Choose what runs and what appears

Write options on lines beginning with #| at the top of an R chunk. Use a unique, descriptive label such as mass-summary; copied chunks need new labels. Unnamed chunks receive automatic names, but explicit labels are easier to navigate and give stable names to results.

OptionRuns code?Shows code?Shows results?
eval: falseNoYesNo new results
include: falseYesNoNo
echo: falseYesNoYes
output: falseYesYesNo

These entries describe each option used alone. Hiding code with echo: false is useful for a figure that readers should see. Hiding a setup chunk with include: false still allows it to load packages and create objects used later. Disabling evaluation prevents that work from happening.

```{r}
#| label: setup
#| include: false
library(tidyverse)
library(palmerpenguins)
```

message: false hides messages, while warning: false hides warnings. Investigate warnings while developing; suppressing them can conceal dropped values or other problems. By default, a code error stops rendering. error: true displays the error and continues, which is useful when a teaching example deliberately demonstrates an error.

Set defaults at the right level
execute:
  echo: false
format:
  html:
    code-fold: true

The execute setting hides code throughout the document unless a chunk overrides it with #| echo: true. For HTML, code folding provides a toggle for code that is included; if echo: false omits the code, there is nothing to fold. Choose included, folded code when collaborators need access to the method. Options specific to knitr, such as collapse and comment, go under knitr: opts_chunk:.

Older R Markdown syntax puts options in the chunk header, such as {r, echo=FALSE}. Quarto accepts this for R, but the #| syntax uses YAML and works across execution languages. Some names change: old-style fig.width becomes fig-width in YAML-style options.

Keep prose connected to calculations

Compute a value before inserting it into text:

mean_mass <- mean(penguins$body_mass_g, na.rm = TRUE)
mean_mass_text <- format(round(mean_mass), big.mark = ",")

The sentence "Mean body mass was `r mean_mass_text` g" renders with 4,202 g. Inline R can also use the form `{r} mean_mass_text`. Keep inline expressions short; store more involved calculations in a chunk.

Hand-typed numbers can remain unchanged after the analysis changes. Inline expressions are evaluated during rendering and connect the prose to the objects used by the analysis. Their freshness still depends on their inputs: if a cached calculation is outdated, inserting its result inline will reproduce that outdated value.

Key Takeaways

  • Distinguish execution from displaying code and results.
  • Labels must be unique within a document.
  • Document execution defaults can be overridden in individual chunks.
  • HTML code folding needs code to be included.
  • Use inline code for computed numbers and format them for readers.
  • Inspect warnings before choosing to hide them.

3.3 Add figures, tables, cross-references and citations

A figure becomes useful evidence when readers can identify it, understand its labels, and find the matching explanation in the text. Quarto can number figures and tables automatically and build citations from a bibliography.

Draw and display figures consistently

fig-width and fig-height control the size at which R draws a figure. These software settings use inches. fig-asp sets height as a proportion of width. For example, fig-width: 6 with fig-asp: 0.618 draws a figure about 6 by 3.7 inches. out-width and out-height control its displayed size in the report.

Drawing a large plot and shrinking it also shrinks its labels. Keep a common drawing width across figures so text sizes remain consistent. Adjust aspect ratio for a particular shape, and use layout-ncol: 2 when two plot outputs belong side by side.

Caption and reference a figure
```{r}
#| label: fig-species-mass
#| fig-cap: "Body mass differs across penguin species"
#| fig-alt: "Gentoo masses are centered above those of Adelie and Chinstrap penguins."
#| fig-width: 6
#| fig-asp: 0.618
#| out-width: "70%"
#| fig-align: center
ggplot(penguins, aes(species, body_mass_g)) +
  geom_boxplot()
```

Gentoo penguins have the highest median mass (@fig-species-mass).

The chunk creates the plot; the fig- label and caption make it a numbered figure. The reference becomes a numbered link, so inserting an earlier figure does not leave the text pointing to the wrong number. Use a caption that helps readers interpret the evidence. Alt text supplies a text alternative for readers using assistive technology; it serves a different role from a short title.

Present a small summary table

A printed tibble looks like console output. Pass the summary to knitr::kable() for a formatted table:

penguins |>
  group_by(species) |>
  summarize(
    measured = sum(!is.na(body_mass_g)),
    median_g = median(body_mass_g, na.rm = TRUE)
  ) |>
  knitr::kable(col.names = c(
    "Species", "Measured birds", "Median body mass (g)"
  ))

Counting measured birds makes the denominator match the mass summary. A count from n() would instead count all rows in the species, including missing mass. For a numbered table, add a chunk label beginning tbl- and tbl-cap; refer to it with @tbl-.... A label without the right prefix does not establish the intended numbered cross-reference. Packages such as gt offer further table styling.

Cite the data and other sources

Store bibliographic entries in a BibTeX file and declare it in the header with bibliography: references.bib. The citation [@gorman2014] appears in parentheses; @gorman2014 becomes a citation in running text. Quarto builds the reference list from the cited entries. A csl: option selects a citation-style file.

Use citation("palmerpenguins") in R to find the package's recommended citation. A citation identifies the source of evidence; the figure caption and surrounding sentence still need to explain what the evidence shows.

Key Takeaways

  • Drawing dimensions and displayed dimensions have different jobs.
  • Use prefixed labels and captions for numbered cross-references.
  • Captions and alt text serve different readers and purposes.
  • Use formatted summaries with clear units and matching observation counts.
  • Declare a bibliography and cite its entry keys in the text.
4

Choose output formats: documents, slides and dashboards

Readers need different forms of the same analysis. An editable draft, a printable report, a presentation, and a dashboard each organize evidence differently. Choose a format from the reader’s task, then adapt the layout and graphics to it. Quarto keeps calculations in the source while letting documents, slides, and dashboards present those calculations in ways that suit reading, discussion, or monitoring.

4.1 Render documents to HTML, PDF and Word

Choose an output format from the way readers will use the report. A browser supports interactive elements; a PDF keeps a fixed page layout; a Word document lets collaborators edit prose. The same source can produce several versions of the analysis.

Set formats and render them

A short header can use format: html. To give each format its own options, nest settings under its name:

format:
  html:
    toc: true
    code-fold: true
  pdf: default
  docx: default

The HTML version has a table of contents and foldable code. toc: true normally includes headings through level three. The other formats use their defaults.

quarto render report.qmd renders the listed formats; quarto render report.qmd --to docx requests Word specifically. R also supports quarto::quarto_render("report.qmd"). RStudio's Render button uses the first listed format, with other choices available from its menu. Check the output you intend to share, since layout and supported features vary across formats.

Match capabilities to readers
FormatUseful forMain setup or sharing issue
HTMLReading on screen and browser interactionInclude supporting resources when sharing
PDF through LaTeXPrinting and fixed pagesInstall a TeX distribution
PDF through TypstFixed pages with Typst typesettingSelect format: typst
Word (docx)Editing and commentsUse a reference document for styles

HTML often stores images and support files beside the main page. Sending just the HTML file can leave broken figures. Set embed-resources: true under html: to bundle images, scripts, and style sheets into the file. Resources fetched while the reader views it, such as online map tiles, still need an internet connection.

format: pdf uses LaTeX. Install a TeX distribution before rendering it; quarto install tinytex supplies a small one. format: typst also produces PDF, using the Typst system included with Quarto. For Word, reference-doc: template.docx under docx: applies styles from an existing document.

Plan figures for each output

Interactive HTML widgets, such as plotly charts, leaflet maps, and DT tables, belong in HTML-based outputs. They do not remain interactive in PDF or Word. Provide static plots and formatted tables for those formats. An HTML report with a map, a printed PDF, and an editable Word draft may share calculations while needing different presentations of the evidence.

A monthly results report for colleagues to comment on suits Word; a fixed board pack suits PDF; an on-screen report with browser interaction suits HTML. Decide this before investing in widgets that the final format cannot use.

Edit the Quarto source when changing the report. Changes made only to a rendered Word or HTML file are lost when it is regenerated. A Quarto project, configured with _quarto.yml, can combine documents into a website or book with shared settings and navigation. It also provides a place for project-wide execution controls.

Key Takeaways

  • Choose output by reading, printing, editing, and interaction needs.
  • Keep format-specific options nested under their format names.
  • Bundled HTML can still need online resources fetched during viewing.
  • LaTeX PDF needs TeX; Typst is another PDF route.
  • Provide static figures and tables for PDF and Word.
  • Change the source so edits survive the next render.

4.2 Present results as slides

A presentation guides people through evidence in a deliberate order. Give each slide one message and enough visual detail to support it. A report's paragraphs usually need to be reorganized before they work on a screen viewed from a distance.

Choose the slide format

Quarto supports browser slides with revealjs, PowerPoint with pptx, and PDF slides with LaTeX-based beamer. They share Markdown and code chunks, but browser features belong to the HTML presentation.

---
title: "How penguin body mass varies"
format:
  revealjs:
    incremental: true
execute:
  echo: false
---

This hides analysis code and reveals list items progressively in revealjs. A level-two heading (##) starts a titled slide. A level-one heading (#) creates a section title slide. A horizontal rule (---) in the body creates a new slide without a title.

Build the argument before the layout

A short talk can move from the question to findings, evidence, limits, and next steps. For the penguin analysis, the question asks whether species differ in body mass. A findings slide can show the boxplot under the title "Gentoo penguins have the highest median mass." A later slide can examine sex differences within species. Data limits belong near the conclusion so readers understand where the findings apply.

Write titles that tell listeners what to take from the evidence. "Body mass by species" names variables; "Gentoo penguins have the highest median mass" states a finding. Put units and readable category names on the plot. Increase plot text size, for example with theme_minimal(base_size = 18), and check the rendered slide at the size viewers will see.

Use revealjs features for pacing

A line containing . . . pauses before the next content. Wrap a particular list in ::: {.incremental} when only that list needs progressive display. Speaker notes live in a notes div:

::: {.notes}
Explain how the measured count differs from the total row count.
:::

Press S during the presentation to open speaker view. Notes let you preserve an explanation without crowding the slide itself.

Columns can keep a figure beside a short interpretation:

:::: {.columns}
::: {.column width="60%"}
A plot goes here.
:::
::: {.column width="40%"}
A short statement interprets the plot.
:::
::::

Replace the placeholder text with the plot chunk and its explanation. Check that the figure remains readable in the narrower space.

Fix overflow at its source

Revealjs uses a fixed slide canvas, 1050 by 700 pixels by default. Excess content can run beyond the bottom. Remove secondary text or split the message before reducing everything to tiny print. Resize figures where useful. A {.smaller} heading class reduces slide text, while {.scrollable} allows scrolling. Scrolling can help a self-paced technical presentation, but an audience still needs a readable sequence during a live talk.

Key Takeaways

  • Use revealjs, pptx, or beamer for the intended delivery format.
  • Level-two headings create titled slides; level-one headings create sections.
  • Build a question–finding–evidence–limits sequence.
  • Keep one message per slide with readable plots and hidden code when appropriate.
  • Use notes and progressive display to support pacing.
  • Inspect rendered slides for overflow.

4.3 Build a dashboard

A dashboard puts a few important results together so readers can inspect them at a glance. It works well for monitoring indicators or comparing views of the same data. A report or slide sequence is better suited to an argument that must be read in order.

Use headings to arrange the page

Set format: dashboard to build an HTML dashboard. Its title appears in a navigation bar. Level-one headings create pages. By default, level-two headings create rows whose cards sit side by side. Set orientation: columns under format: dashboard: to make level-two headings create columns instead.

A row attribute such as ## Overview {height=35%} assigns a share of the available space. Each output-producing code chunk becomes a card. #| title: gives the card a readable title. Plain text can occupy a ::: {.card} div.

Build a value box and a plot card
---
title: "Penguin overview"
format: dashboard
execute:
  echo: false
---

```{r}
#| include: false
library(tidyverse)
library(palmerpenguins)
```

# Measurements

## Overview {height=30%}

```{r}
#| content: valuebox
#| title: "Birds with recorded body mass"
list(icon = "clipboard-data", color = "primary",
     value = sum(!is.na(penguins$body_mass_g)))
```

## Distributions {height=70%}

```{r}
#| title: "Body mass by species"
#| fig-alt: "Gentoo penguins have a higher median body mass than Adelie and Chinstrap penguins."
ggplot(penguins, aes(species, body_mass_g)) +
  geom_boxplot() +
  labs(x = "Species", y = "Body mass (g)",
       caption = "Data: palmerpenguins")
```

The value box shows 342 measured masses. Its title says exactly what it counts; the full table has 344 birds. The second row holds a boxplot card. Add another output chunk to that row for a second card, such as a scatterplot, or add a new level-one heading for a separate page of details.

A value box returns an R list with a value and optional icon and color. Icons use Bootstrap Icons names. Choose a title and unit that make the number interpretable. A count of rows, a count of nonmissing measurements, and a count of distinct species answer different questions even when all appear as large numbers.

Know what updates in the browser

In a static dashboard, R runs when the source is rendered. A reader sees the resulting HTML. A browser widget can offer sorting, tooltips, or zooming using data already sent to the page. Those interactions do not rerun R. A control that needs a new R calculation requires a running R server.

Render again when the underlying data change. Parameters can produce separate dashboards for different periods or groups. Merely reopening an old HTML page does not import the newest data.

Keep the card count small enough for labels and plots to remain readable. Put headline indicators near the top and supporting distributions below. Several unlabeled value boxes or many tiny plots make the page harder to interpret, even when each calculation is correct.

Key Takeaways

  • Dashboard headings define pages and rows or columns.
  • Output-producing chunks become cards; titles identify their content.
  • Value boxes highlight one clearly named number.
  • Static dashboard R code runs at render time.
  • Browser widgets can interact without rerunning R.
  • Refresh the render when data change and keep the layout readable.
5

Keep the analysis reproducible

Rebuilding a report requires more than keeping its final HTML page. Preserve the input data, executable steps, software setup, and instructions needed to run the work again. Parameters let one source serve multiple groups, while caching and freezing can reduce repeated computation. Check which inputs each saved result depends on so speed does not come at the cost of reporting outdated findings.

5.1 Make a report that anyone can re-render

A reproducible report lets someone start with the same data and code and rebuild the results. The source must carry the steps that produced each number, table, and figure. A successful interactive session is useful while developing, but a clean render tests whether those steps are complete.

Keep the project portable

Give the analysis its own project folder. An RStudio Project records its project entry point in a .Rproj file. Organize raw data, reusable code, and outputs in clearly named subfolders such as data/, R/, and output/.

Use a relative path from the document's working directory, or build a path from the project root:

raw <- readr::read_csv(here::here("data", "penguins.csv"))

A path tied to one user's desktop will not work for a collaborator. Avoid using setwd() to patch paths for each machine. State where input data belong so the project layout and code agree.

Treat raw data as read-only. Write cleaning rules in code and save cleaned copies only as reproducible outputs. A manual spreadsheet correction changes the evidence without preserving the operation that produced the change. Keep the original value available and explain the correction in the analysis record.

Control random work and record software

A random sample should be repeatable when the analysis needs it:

set.seed(2026)
example_birds <- penguins |> slice_sample(n = 10)

Set the seed before the random operation. It makes that operation repeatable with the same software setup and sequence of random calls. It does not document the data, restore packages, or explain cleaning decisions.

sessionInfo() records R, operating-system, and loaded-package versions. For a project package environment, use renv:

renv::init()
renv::snapshot()

Run these environment-management commands while setting up or maintaining the project. The lockfile renv.lock records package versions. A collaborator uses renv::restore() to install the recorded versions. Keep the data, source, and instructions too; a package lockfile is only one part of reproducing an analysis.

Preserve changes and handover instructions

Use Git to record source changes with meaningful messages and recover earlier versions. Commit the analysis source and relevant project configuration. Ordinary rendered reports can be regenerated. Add a short README explaining the question, data source, required setup, and source document to render. Another reader should be able to locate the starting point without reconstructing your console history.

Test from a clean start

Restart R and render the entire report. If an error appears, read the first failing chunk and recreate the problem by running chunks from the top in a restarted session. Check for console-only objects, packages loaded only interactively, incorrect paths, and duplicate labels.

rm(list = ls()) removes objects but leaves packages and options in place, so it is not a replacement for restarting R. When checking whether calculations can rebuild from inputs, bypass or refresh caches as well. A cached result may conceal a missing dependency. Edit the source after a failure; changing only the rendered HTML or Word file cannot fix the next render.

Key Takeaways

  • A reproducible report rebuilds results from data and code.
  • Use a portable project layout and preserve raw data.
  • Set a seed before random steps and record software versions.
  • renv records and restores project package versions.
  • Git and a README preserve history and explain how to run the project.
  • Restart R and check a full render, including cache freshness.

5.2 Reuse reports with parameters and save time with caching

Parameters let one analysis produce reports for several groups or periods. Caching saves time by reusing computations. Both features need care: the title must match the chosen data, and saved results must match the inputs that produced them.

Declare and use a parameter
params:
  species: "Adelie"

R code reads the parameter from params:

selected <- penguins |> filter(species == params$species)

Use the same parameter in visible text, such as the heading # Body mass of `r params$species` penguins. A hard-coded species name can leave a Gentoo analysis labeled "Adelie." Check names exactly; params$specis does not retrieve params$species.

The default selects 152 Adelie rows. Supply another value from the terminal:

quarto render report.qmd -P species:Gentoo

A YAML file of values can be passed with --execute-params params.yml. From R, specify both parameter values and a distinct output name:

quarto::quarto_render(
  "report.qmd",
  execute_params = list(species = "Gentoo"),
  output_file = "report-gentoo.html"
)

Use iteration to make several variants without copying and editing the source:

species <- c("Adelie", "Chinstrap", "Gentoo")
purrr::walk(species, function(sp) {
  quarto::quarto_render(
    "report.qmd",
    execute_params = list(species = sp),
    output_file = paste0("report-", tolower(sp), ".html")
  )
})

The three reports cover 152, 68, and 124 birds. Distinct output names prevent one variant from replacing another.

Cache expensive chunks with their dependencies

#| cache: true saves a chunk's results. Set cache: true under execute for document-wide caching. knitr checks the chunk's code and options before reusing its stored work. An external CSV can change without either of those changing, so an unchanged chunk can still produce stale output.

When both chunks are cached, declare an upstream dependency with #| dependson: raw-data. For uncached upstream work, track its relevant value in cache.extra or leave the consuming calculation uncached. For a file read inside a cached chunk, make its modification time part of the cache key:

#| cache: true
#| cache.extra: !expr file.mtime("data/raw.csv")
raw <- readr::read_csv("data/raw.csv")

Include changing parameters in a cache key when a cached calculation depends on them, or leave that calculation uncached. To force saved chunks to recompute, use quarto render report.qmd --cache-refresh.

Distinguish freezing from chunk caching

A project can set freeze: auto under execute in _quarto.yml. During a full project render, it reuses a document's computations unless that document's source changed. Stored results go into _freeze, which belongs in version control when the project uses freezing.

A changed input file alone does not trigger freeze: auto. Rendering the individual document bypasses freezing; refresh its cache too if caching is enabled. Freezing controls document execution during project builds, while caching controls reuse inside execution.

Key Takeaways

  • Parameters must drive data selection and visible labels.
  • Use distinct output names when rendering several variants.
  • Chunk caches need dependencies for changing files, upstream objects, and parameters.
  • Use --cache-refresh to force cached work to rerun.
  • Project freezing and chunk caching control different kinds of reuse.
6

Communicate findings to an audience

Communication begins with the reader’s question. Select the evidence that answers it, write the findings with useful numbers and units, and make each display readable and accessible. An honest account also explains the sampled setting, missing information, and choices that affect the results. These details help readers distinguish an observed pattern from an explanation that still needs further evidence.

6.1 Plan and write a report for its readers

A report helps a particular reader answer a particular question. Decide who will use it before choosing what to show. The full exploration is a record of your work; the final report selects the evidence readers need to understand the answer.

Choose the audience and structure

Decision-makers usually need the findings, their practical meaning, and important limits. Collaborators need enough method and code to understand or reproduce the analysis. While working, you need a notebook that records choices, trials, and dead ends. A single analysis can support all three audiences through different presentations.

For a short report, begin with the question and why it matters. State the main findings early. Follow each finding with evidence and an interpretation, then describe limitations and next steps. Fold code or place it in an appendix when the main readers need the result without the implementation.

Exploratory plots help you discover a pattern. Explanatory plots help another person understand a selected finding. Keep relevant contrary evidence and consequential limitations, but leave unrelated trials in the notebook. Showing every plot can hide the result among details.

Write a finding with its evidence

A findings sentence should say what changed or differed, how much, and where the evidence appears. For example: "Gentoo penguins have a median body mass of 5,000 g, compared with 3,700 g for Adelie and Chinstrap penguins (Figure 1)." The sentence interprets the comparison and supplies units. "This figure is a boxplot of body mass" only describes the display.

Use inline R for computed numbers. Round to a useful precision and include thousands separators in prose. State the number of observations used by a result; the total row count can differ from the count with a recorded measurement. A mean of 4,201.754 g carries more digits than a reader needs here; 4,202 g is clearer.

Make the figure carry its message

Use readable labels and units, a finding-based title, and an appropriate source caption:

ggplot(penguins, aes(
  x = species, y = body_mass_g, fill = species
)) +
  geom_boxplot() +
  scale_fill_viridis_d(guide = "none") +
  labs(
    title = "Gentoo penguins have the highest median mass",
    x = "Species", y = "Body mass (g)",
    caption = "Data: palmerpenguins"
  ) +
  theme_minimal(base_size = 13)

Species are identified by axis labels as well as color. The legend can be removed because it repeats that information. Remove clutter when it distracts from the comparison, while preserving the information needed to read the evidence.

Make access part of the design

Add alt text to every figure, describing the comparison and the important pattern. Choose distinguishable colors, such as a viridis palette, and provide labels or shapes as another way to identify groups. Readers should not have to distinguish colors to find the conclusion. Check plot text in the rendered output; a figure that is clear in the plotting pane may become unreadable when reduced for a page or slide.

Key Takeaways

  • Choose what to show from the reader's needs.
  • Lead with findings, then give evidence, limits, and next steps.
  • Interpret results with numbers, units, and observation counts.
  • Use meaningful titles, readable labels, and source captions.
  • Provide alt text and a way to distinguish groups without color.

6.2 Report exploratory findings honestly

An honest report matches the strength of its claims to the evidence. Exploration discovers patterns worth investigating; it also involves many choices about groups, missing values, displays, and wording. Readers need enough of that context to judge a finding fairly.

Match the claim to the analysis

Patterns found while searching one dataset are hypotheses. Some will arise by chance. Checking a hypothesis on the same data that suggested it is circular; use new data or an appropriate formal method when confirmation matters. Wording such as "in this dataset" identifies the observed setting without weakening the measurement itself.

Association in observational data is different from a causal effect. Fair-cut diamonds have a higher median price than Ideal-cut diamonds, but their median sizes are also larger. A report that attributes the price gap to cut ignores this third variable. Describe what was observed and inspect size before proposing an explanation.

Subgroups can change the direction of an association. The overall bill-length and bill-depth correlation among penguins is about −0.24, while each species has a positive correlation. If that contrast changes the interpretation, show the subgroup results alongside the overall result. Selecting just the combined plot would hide relevant evidence.

State what was measured and what is missing

Identify the objects, place, and time: these penguins were measured on three islands near Palmer Station in 2007–2009. State the usable count for each result. The dataset contains 344 birds, but only 342 have recorded body measurements, and 11 have no recorded sex.

Give group counts as well as summaries. There are 68 Chinstrap and 152 Adelie birds. Other things being equal, smaller groups give less precise estimates, but variability and sampling also affect precision. Sample size alone cannot tell readers how representative a group is.

Explain consequential decisions

Record what was removed or replaced, the reason, and the effect on the analysis. For example: "Nine suspect diamond widths were set to missing: seven zeros and values of 31.8 and 58.9 mm." If you add "the conclusions were unchanged," first compare the analysis with and without those values. A cleaning rule is part of how the result was produced, not an untidy detail to hide.

Keep relevant failed analyses and contradictory evidence in the record. A final report can be concise while still explaining choices that materially affect its conclusions. Selecting only supportive plots is cherry-picking and gives a false account of the evidence.

Use scales and effect sizes fairly

A bar's length represents its value, so its value axis should start at zero. A truncated baseline exaggerates the visual difference between bars. Side-by-side plots intended for direct comparison need compatible scales; otherwise equal-looking distances can represent different changes.

Describe the size of a difference with words and numbers. "The Gentoo median is about 1,300 g higher" tells the reader more than an absolute claim that the analysis "proves" a species effect. Distinguish the observed difference, its possible explanations, and the next evidence needed to test those explanations.

Key Takeaways

  • Exploratory patterns need further evidence for confirmation.
  • Check third variables before making causal claims.
  • Report subgroup results when they change the interpretation.
  • State the sampled setting, usable counts, and missing information.
  • Disclose cleaning choices and check claims about their effect.
  • Use fair scales and avoid cherry-picking.

Exploratory Analysis in R examples

6 Walkthroughs

1

Start an exploration and inspect its data

12 steps
Develop a question about penguin measurements, inspect a distribution, and handle suspect or missing values.
  1. 1
    IntroductionMove from a table to a useful question

    An exploration develops through questions. Begin by learning what the rows and variables mean, then let a plot or summary suggest the next comparison.

    We will inspect penguin measurements, describe the body-mass distribution, and decide how unusual or missing values affect the information available. Keep the code and your reasons together so later decisions have a visible record.

  2. 2
    ExampleInspect the first rows and counts

    Load the intended data and take a structural look:

    library(tidyverse)
    library(palmerpenguins)
    glimpse(penguins)
    penguins |> count(species)
    

    There are 344 rows and eight columns. Each row represents one bird, and species counts are 152 Adelie, 68 Chinstrap, and 124 Gentoo. The unequal counts matter when later plots compare frequencies across groups.

  3. 3
    ExplanationName the comparison

    "Are penguins heavy?" leaves the comparison unclear. Ask, "How does body mass differ between species, and does that difference hold within each sex?"

    This names a numerical variable, groups, and a subgroup check. A histogram can introduce the overall variation; boxplots by species and sex can then investigate covariation. The question helps choose the display before the display becomes the conclusion.

  4. 4
    ChallengeRefine a broad question

    A new table records plant species and leaf length in millimeters. Rewrite "Are the leaves different?" as a focused comparison.

    ---reveal---

    One useful question is "How does leaf length vary between plant species?" It names the measurement and groups. It leads to group distributions and numerical summaries; a yes-or-no judgment without a named measurement would leave the analysis unclear.

  5. 5
    ExampleBuild the first histogram

    Plot recorded body masses with a chosen interval width:

    ggplot(penguins, aes(body_mass_g)) +
      geom_histogram(binwidth = 200)
    

    Each bar groups masses in a 200 g interval. Inspect the common ranges, tails, and possible clusters. Try 100 and 500 g too: narrow bins can emphasize noise, and broad bins can conceal structure that would suggest a useful subgroup comparison.

  6. 6
    ExampleAttach center and spread

    Summarize the recorded masses:

    penguins |> summarize(
      median_g = median(body_mass_g, na.rm = TRUE),
      iqr_g = IQR(body_mass_g, na.rm = TRUE)
    )
    

    The median is 4,050 g and IQR 1,200 g. The quartiles are 3,550 and 4,750 g, so the middle half spans that interval. The two missing masses are omitted from these calculations; they have not become measured zeros.

  7. 7
    ChallengeChoose summaries for a long tail

    A few unusually large recorded waiting times pull an average upward. What center-and-spread pair would be more resistant, and what should you still inspect?

    ---reveal---

    Use the median and IQR and inspect the distribution and unusual records. These summaries resist a few extremes better than mean and standard deviation. Their use does not decide whether the unusual records are genuine or erroneous.

  8. 8
    ExampleFind rare unusual widths

    Diamond width is stored in y, in millimeters. A coordinate zoom exposes very short histogram bars:

    ggplot(diamonds, aes(y)) +
      geom_histogram(binwidth = 0.5) +
      coord_cartesian(ylim = c(0, 50))
    

    Inspection finds seven zero widths and values of 31.8 and 58.9 mm. Look at those records and their context before assigning a cleaning rule. The plot alone cannot explain why a value is unusual.

  9. 9
    TipPreserve the rest of a record

    If a width is judged wrong, replace that measurement in a cleaned copy:

    diamonds_clean <- diamonds |>
      mutate(y = if_else(
        y < 3 | y > 20, NA_real_, y
      ))
    

    The other fields remain usable. Record the reason for the rule and compare conclusions with and without the affected values. Deleting an entire row would also remove valid prices and categories that other analyses could use.

  10. 10
    ExplanationInvestigate missingness

    Missing values can show where recording differs. Create an indicator and compare it across groups:

    penguins |>
      mutate(sex_missing = is.na(sex)) |>
      count(species, sex_missing)
    

    Six Adelie and five Gentoo birds lack recorded sex. For a mass-only summary, those birds can still contribute when their mass is known. Restrict missing-value removal to the columns required for the current question.

  11. 11
    ChallengeKeep the right observations

    A table has 110 rows. Eight lack category labels, three lack mass, and two lack both. For a mass-only histogram, how many rows can supply a position, and why avoid unrestricted drop_na()?

    ---reveal---

    There are 107 recorded masses. Unrestricted deletion would also remove the six rows missing only a category label. Check the row requirements from the question before preparing the plotting data.

  12. 12
    RecapKeep a record of the reasoning

    Begin with the meaning of a row, group counts, units, and missingness. Use a focused question to choose a plot, then describe its center, spread, and shape.

    When a value looks wrong, inspect it and preserve useful information elsewhere in its row. A later reader should be able to see both the transformation and the reason it was made, including whether it changed the result.

2

Compare distributions and uncover hidden patterns

14 steps
Work through group comparisons, categorical denominators, and a numerical subgroup reversal.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionChoose a relationship view
  2. 2
    ExampleRead the species boxplots
  3. 3
    ExplanationDistinguish fences from whiskers
  4. 4
    Key InsightSeparate shape from sample size
  5. 5
    ChallengeInvestigate a surprising group gap
  6. 6
    ExampleCount and complete the grid
  7. 7
    ExampleAnswer the within-island question
  8. 8
    ChallengeReverse the conditioning group
  9. 9
    ExampleDescribe a numerical pair
  10. 10
    TipReveal crowded regions
  11. 11
    ExampleInspect the bill relationship by species
  12. 12
    ChallengeExplain a reversal without a causal claim
  13. 13
    ChallengePlan a fair combined investigation
  14. 14
    RecapRead what a summary leaves out
3

Build a report that renders on its own

13 steps
Create a small Quarto source, control its code display, and connect evidence to prose.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionKeep explanation beside computation
  2. 2
    ExampleStart with a header and setup
  3. 3
    ExplanationRun the complete source
  4. 4
    ChallengeRepair a hidden dependency
  5. 5
    ExampleHide setup, preserve its work
  6. 6
    ExampleShow a result without its code
  7. 7
    ExampleInsert a formatted number
  8. 8
    ChallengeKeep a plot visible
  9. 9
    ExampleName and describe the figure
  10. 10
    ExampleFormat a table and identify its sources
  11. 11
    ChallengeRepair a figure reference
  12. 12
    ChallengeCheck one complete evidence chain
  13. 13
    RecapCheck source, execution, and presentation
4

Choose the right report, slides, or dashboard

12 steps
Adapt one analysis to editing, presentation, and monitoring needs.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionStart with the reader’s task
  2. 2
    ExplanationMatch the document format
  3. 3
    TipShare the resources the report needs
  4. 4
    ChallengeChoose an editable draft
  5. 5
    ExampleLay out the talk’s argument
  6. 6
    TipPreserve detail without overcrowding
  7. 7
    ChallengeImprove an overflowing slide
  8. 8
    ExampleArrange the dashboard
  9. 9
    ExampleName one value precisely
  10. 10
    ChallengeRefresh a static page
  11. 11
    ChallengeChoose outputs for two uses
  12. 12
    RecapInspect the final form
5

Rebuild and reuse a report safely

11 steps
Make an analysis portable, produce parameter variants, and diagnose stale execution results.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionPreserve the path from inputs to results
  2. 2
    ExampleMake the project portable
  3. 3
    ExplanationRecord the software and random state
  4. 4
    ChallengeTest a fresh start
  5. 5
    ExampleUse one input in data and text
  6. 6
    ExampleRender separate variants
  7. 7
    ExplanationTrack what a cached result depends on
  8. 8
    ChallengeFind the stale import
  9. 9
    Key InsightDistinguish two reuse layers
  10. 10
    ChallengeRebuild after an external update
  11. 11
    RecapMake dependencies visible
6

Turn exploration into a clear, honest report

10 steps
Select evidence for readers, make figures accessible, and keep claims within the data.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAnswer the reader’s question
  2. 2
    ExplanationChoose the evidence readers need
  3. 3
    ExampleWrite a finding with units
  4. 4
    TipMake the figure accessible
  5. 5
    ChallengeRevise a reader-facing display
  6. 6
    ExplanationSeparate an observation from a cause
  7. 7
    ExampleDescribe the data and the decisions
  8. 8
    ChallengeRepair a claim about generality
  9. 9
    ChallengeAudit the final presentation
  10. 10
    RecapGive readers a fair account

Exploratory Analysis in R practice questions

50 Practice Questions in 5 sets

Set 1: Read data and build a report10 Practice Questions

Question 1 of 10

An analyst asks, "How spread out are the measured leaf lengths?" What kind of exploratory question is this?
  1. A comparison of two numerical variables
  2. A variation question about one variable
  3. A comparison of two categorical variables
  4. A covariation question about plant groups
Show answerHide answer
Answer: B
The question concerns the distribution of leaf length alone, so it asks about variation. A covariation question would connect length with another variable, such as plant group or light exposure. The fact that many leaves were measured does not make it a two-variable question.

Question 2 of 10

A table records the mass of each soil sample in grams. What plot groups nearby masses and shows how often they occur?
  1. A bar chart for every distinct mass
  2. A scatterplot of row number and mass
  3. A count plot of mass and sample name
  4. A histogram with mass intervals
Show answerHide answer
Answer: D
A histogram groups nearby numerical values into intervals and displays their frequencies. A bar chart of each distinct recorded mass counts exact values separately, which can obscure the distribution of a continuous measurement. The intervals should be expressed in grams.

Question 3 of 10

A water-sample row contains an impossible negative volume but valid location and date fields. How should a cleaned copy preserve the useful information?
  1. Replace the volume with NA and retain the row.
  2. Replace every field with NA and retain the row.
  3. Remove the row before analyzing any other field.
  4. Replace the volume with zero and retain the row.
Show answerHide answer
Answer: A
Replacing the judged-wrong volume with NA preserves the location and date for analyses that can use them. Removing the whole row discards valid information unnecessarily. Zero would create a measured volume that the record does not support, so the cleaning decision should also be documented.

Question 4 of 10

Two departments have 45 and 210 recorded task durations. How can overlaid frequency polygons compare their distribution shapes fairly?
  1. Use counts and give both lines the same color.
  2. Use counts and remove the larger department’s tail.
  3. Use density scaling separately for each department.
  4. Use density scaling after combining both departments.
Show answerHide answer
Answer: C
Density scaling gives each department’s curve area one, so the comparison focuses on shape despite unequal counts. A count-based curve partly reflects the much larger sample, not just the distribution of durations. Scaling the combined data would not normalize the two groups separately.

Question 5 of 10

Of 90 samples from Site A, 27 are clay. Across all sites there are 60 clay samples. What proportion of Site A’s samples are clay?
  1. 45%
  2. 30%
  3. 15%
  4. 67%
Show answerHide answer
Answer: B
The question fixes Site A as the group, so use its 90 samples as the denominator: 27 of 90 is 30%. Dividing by all 60 clay samples gives 45%, but that answers where clay samples came from. The numerator is the same while the conditioning group changes.

Question 6 of 10

A scatterplot shows a tight U-shaped relationship, but its correlation is close to zero. How should the analyst interpret these results?
  1. The plot must be wrong because correlation is zero.
  2. The variables have a strong positive linear relationship.
  3. The variables have no useful relationship in this sample.
  4. The variables have a strong curved, weakly linear pattern.
Show answerHide answer
Answer: D
Correlation summarizes a linear relationship, so a value near zero can coexist with a clear U-shaped pattern. The scatterplot supplies the form that a single coefficient misses. Calling the variables unrelated would discard visible evidence merely because it is not well described by a straight line.

Question 7 of 10

A report uses cleaned, created only in the R console. Its plot runs interactively but rendering says the object is missing. What change addresses the cause?
  1. Save the plotted image and leave the code unchanged.
  2. Run View(cleaned) at the beginning of the report.
  3. Create cleaned in an earlier executable chunk.
  4. Hide the plot’s code with echo: false.
Show answerHide answer
Answer: C
Rendering starts a fresh R session, so it cannot use an object created only in the console. An earlier chunk must import or create cleaned before the plot uses it. Hiding code changes presentation, not the existence of objects during execution.

Question 8 of 10

Colleagues need to edit a report’s prose and add comments. What Quarto output format best fits that task?
  1. Word with format: docx
  2. PDF with format: pdf
  3. Slides with format: beamer
  4. HTML with format: html
Show answerHide answer
Answer: A
Word output supports an editable draft that colleagues can comment on. PDF is useful for fixed page layout and printing, but does not serve the same text-editing workflow. Choose the format from how the readers will use the report, then inspect the generated version.

Question 9 of 10

A report draws a random sample during rendering. What R call should precede the sampling step to make that random work repeatable?
  1. sessionInfo()
  2. renv::snapshot()
  3. set.seed(812)
  4. rm(list = ls())
Show answerHide answer
Answer: C
set.seed(812) sets the starting state before the random operation, allowing it to repeat with the same software setup and sequence of random calls. sessionInfo() records the environment but does not set that state. The seed must come before the sampling step, not after it.

Question 10 of 10

A manager asks which packaging line has lower typical scrap mass. The overall medians are 18 g for A and 14 g for B, but A has lower medians within both product types. A handles more of the heavier product type. The notebook also has unrelated plots. How should a short decision report present the comparison?
  1. Lead with B’s lower overall median, call B more efficient, and omit the product plots.
  2. Present overall and within-type findings, use the relevant plots, and make code optional.
  3. Lead with A’s lower within-type medians, omit the overall result, and make code optional.
  4. Present every notebook plot and all code before explaining the comparison of the lines.
Show answerHide answer
Answer: B
Readers need the overall result and the within-type pattern because product composition changes the interpretation of the line comparison. Select the relevant plots and interpret them early, with code available according to the audience’s needs. Reporting only B’s lower overall median would conceal the stated reversal.
Set 2: Control output and inspect relationships10 Practice Questions

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

Question 1 of 10

A team wants to compare routes using trip duration. Its table records route, distance in kilometers, and duration in minutes for each trip. What question makes this comparison specific without assuming a causal effect?
  1. "How long do trips take when all routes are pooled?"
  2. "How much does changing a route cause duration to fall?"
  3. "How does the longest trip establish each route’s efficiency?"
  4. "How does typical trip duration differ between routes?"
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A boxplot has first quartile 12 mm and third quartile 20 mm. What is its interquartile range?
  1. 8 mm
  2. 16 mm
  3. 12 mm
  4. 32 mm
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Across all devices, operating temperature and battery life have a negative association. Within each device model, the association is positive. Models with higher usual temperatures have lower usual battery life. What explains the combined result?
  1. The negative combined trend shows every model loses battery life as it warms.
  2. Positive within-model trends make the combined negative trend impossible.
  3. Between-model differences can outweigh the positive within-model patterns.
  4. The combined trend becomes positive when device counts are equalized.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A plot chunk should run and show its figure, while hiding the R code. What chunk option supplies that behavior?
  1. #| eval: false
  2. #| output: false
  3. #| echo: false
  4. #| include: false
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A figure chunk has label: fig-growth and fig-cap: "Growth over time". What text inserts its numbered reference into a sentence?
  1. [Growth over time]
  2. @growth
  3. #fig-growth
  4. @fig-growth
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A presentation needs a section title "Findings" followed by an ordinary titled slide "Energy use fell." What Markdown heading sequence gives that structure?
  1. ## Findings followed by # Energy use fell
  2. # Findings followed by ## Energy use fell
  3. # Findings followed by # Energy use fell
  4. ## Findings followed by ## Energy use fell
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A saved static dashboard has a sortable table. The input CSV changes after rendering, and a reader sorts that table. What happens to the displayed data?
  1. Sorting rearranges the data already stored in the page.
  2. Sorting reruns the R chunk using the changed CSV.
  3. Sorting imports the changed CSV into the saved page.
  4. Sorting refreshes only the rows visible on the screen.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A report defaults to region "North". Its filter uses params$region, but its heading is fixed as "North". An analyst renders South and East variants to the same output filename. What changes are needed?
  1. Keep both settings and call set.seed() before rendering every variant.
  2. Use a parameterized heading and leave every variant at the default value.
  3. Keep the fixed heading and give each region a distinct output filename.
  4. Parameterize the heading and give every region its own output file.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An analyst removes suspect values and writes, "This did not change the conclusions," before comparing results. What check is needed to support that sentence?
  1. Count the remaining rows and use the same conclusion.
  2. Compare the analysis with and without the affected values.
  3. Confirm that the cleaned figure has fewer extreme points.
  4. Hide warnings and render the cleaned report again.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A report in a project’s top folder reads data/samples.csv. A collaborator copies the whole project with its folder structure intact. Why is this path more portable than one naming the original user’s desktop?
  1. It locates the data relative to the report’s folder.
  2. It automatically installs any packages needed for import.
  3. It embeds the CSV inside every rendered output file.
  4. It prevents anyone from changing the raw input values.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Check denominators and dependencies10 Practice Questions

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

Question 1 of 10

A mass histogram shows one broad peak with 800 g bins and two clusters with 100 g bins. What should the analyst do before describing the shape?
  1. Use only the broad bins because they hide random detail.
  2. Use only the narrow bins because detail establishes two groups.
  3. Compare binwidths and inspect the distributions by subgroup.
  4. Average the bin heights to produce one preferred peak.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A table has 240 rows: 15 lack category labels, 6 lack mass, and 4 lack both. An analyst uses unrestricted drop_na() for a mass-only summary. No other fields are missing. How many usable mass records are lost unnecessarily?
  1. 4
  2. 6
  3. 15
  4. 11
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Site P has 12 clay and 28 sand samples; Site Q has 24 clay and 96 sand samples. An analyst says clay makes up more of Site Q because it has twice as many clay samples. What comparison addresses that claim?
  1. Clay is 30% at P and 20% at Q, so its share is higher at P.
  2. Clay is 10% at P and 20% at Q, so its share is higher at Q.
  3. Clay is one third at P and two thirds at Q, so its share is higher at Q.
  4. Clay is 43% at P and 25% at Q, so its share is higher at P.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A setup chunk must load packages and create objects without displaying its code or results. What option should it use?
  1. #| eval: false
  2. #| include: false
  3. #| echo: false
  4. #| output: false
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A species table contains 80 rows, with 7 missing mass measurements. The report gives a median calculated with na.rm = TRUE. What count should accompany that median as its measured sample size?
  1. 80 observations
  2. 7 observations
  3. 87 observations
  4. 73 observations
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A report must be emailed as one HTML file with its local plots, but also uses map tiles fetched when viewed. What does embed-resources: true accomplish?
  1. It bundles plots and also makes the live map tiles available offline.
  2. It bundles local resources, while the map tiles can still need internet.
  3. It converts all widgets to static plots and removes the map tile request.
  4. It embeds only prose, so every plot still needs a separate local folder.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A revealjs slide contains a readable plot and six paragraphs, with the last paragraph off the bottom. How should the author improve a live presentation?
  1. Split the explanation into focused slides and retain readable plot text.
  2. Reduce every font until all six paragraphs fit on the same slide.
  3. Keep the source unchanged because browser slides expand to the text.
  4. Move the plot below the six paragraphs and keep the fixed slide size.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A report renders only after its author loads dplyr in the console. Its import also names the author’s absolute desktop path. What combination addresses both problems for a collaborator?
  1. Load dplyr in a source chunk and retain the author’s absolute desktop import path.
  2. Use portable project paths and rely on dplyr remaining loaded in the console.
  3. Load dplyr in a source chunk and use portable paths from the shared project layout.
  4. Record package versions and restart R, leaving package loading and paths unchanged.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A cached chunk reads a CSV directly. The CSV is replaced with a newer file of the same byte size, while the chunk code stays unchanged. What option tracks the file’s modification time in the cache key?
  1. #| cache.extra: !expr file.size("data/raw.csv")
  2. #| cache.extra: !expr file.mtime("data/raw.csv")
  3. #| cache.extra: "file.mtime(data/raw.csv)"
  4. #| cache.extra: !expr file.exists("data/raw.csv")
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A report compares bar heights representing mean output per machine. Where should the bar chart’s value axis begin?
  1. At the smallest group mean
  2. At the overall group mean
  3. At the first quartile of output
  4. At zero on the value scale
Show answerHide answer

Save this lesson to see this answer.

Set 4: Diagnose reports before sharing10 Practice Questions

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

Question 1 of 10

A team wants to compare individual trip-duration distributions by route. It receives one row per route with the mean duration and trip count. What additional data and plot would let it investigate center, spread, and unusual trips?
  1. Obtain trip-level durations and compare route distributions with boxplots or histograms.
  2. Obtain trip-level durations and use one pooled histogram without separating routes.
  3. Use route means as individual durations, weighting each by its route’s trip count.
  4. Obtain trip-level durations and report only a mean and count for each route.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An analyst wants to inspect very tall histogram bars more closely without changing the data used to calculate them. What ggplot2 addition is appropriate?
  1. ylim(0, 40)
  2. scale_y_continuous(limits = c(0, 40))
  3. coord_cartesian(ylim = c(0, 40))
  4. filter(count <= 40) before plotting
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Facility A’s jobs have longer median duration than Facility B’s. A handles mostly complex jobs; B handles mostly simple jobs. Their within-type plots show A has shorter durations for both job types. What should a comparison report explain?
  1. A is slower overall, so its process must cause longer durations.
  2. B is slower within types, so its overall median must be higher.
  3. The within-type comparisons are irrelevant to facility performance.
  4. The combined comparison mixes job type and duration patterns.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A scatterplot of 70,000 numerical pairs looks like one dark patch. What change can reveal where observations are concentrated without discarding rows?
  1. Draw opaque points with a larger point size.
  2. Use geom_bin2d() to color cells by their counts.
  3. Use geom_bar() to count each horizontal value.
  4. Use one median point for the entire dataset.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A saved report renders prose but never executes its R chunks. Its extension is .md. What source change enables executable Quarto content?
  1. Rename it to .qmd and render that source.
  2. Rename it to .html and render that source.
  3. Keep .md and hide code using echo: false.
  4. Keep .md and replace headings with YAML keys.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

An HTML report has document-wide echo: false and code-fold: true. A collaborator must be able to inspect one calculation while its code starts collapsed. How should that chunk be configured?
  1. Keep echo: false and set include: false.
  2. Keep echo: false and set eval: false.
  3. Set echo: true so the included code can be folded.
  4. Set output: false so the hidden code becomes visible.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A dashboard uses the default layout. What does a level-one Markdown heading create?
  1. A row of cards
  2. A page in the navigation
  3. A dashboard value box
  4. A single plot card
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A collaborator has a project’s renv.lock and wants the package versions it records. What renv command performs that setup?
  1. renv::snapshot()
  2. set.seed(924)
  3. sessionInfo()
  4. renv::restore()
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A scatterplot identifies groups only by red and green points. The source includes clear axis labels but no alt text. What improvement addresses both problems?
  1. Keep the colors and add a longer plot title.
  2. Use smaller points and remove the group legend.
  3. Add shapes or labels for groups and meaningful alt text.
  4. Replace group labels with more decimal places on the axes.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Two training groups have different completion rates. Participants chose their own group, prior experience differs, and only supportive comparisons are shown. How should the report be revised?
  1. Report observed rates, examine prior experience, and include relevant contrary evidence.
  2. Report observed rates and prior experience, retaining only plots that support the recommendation.
  3. Report all relevant comparisons, interpreting the gap as causal because the sample is large.
  4. Examine prior experience and state limitations, omitting the observed completion-rate comparison.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Combine analysis, execution, and communication10 Practice Questions

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

Question 1 of 10

A few extreme recorded masses pull the mean far above the main cluster. What pair of summaries gives a more resistant description of center and spread?
  1. Mean and standard deviation
  2. Median and standard deviation
  3. Mean and interquartile range
  4. Median and interquartile range
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

The table has 18 red and 42 blue items in Batch A, and 30 red and 10 blue in Batch B. What code structure answers "What share of each batch is red?" and what result follows?
  1. Group by color; red is 37.5% from A and 62.5% from B.
  2. Group by batch; red is 30% in A and 75% in B.
  3. Group by batch; red is 43% in A and 300% in B.
  4. Use the full table total; red is 18% in A and 30% in B.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Two sensors each show a strong curved relationship between temperature and output. Their combined correlation is near zero, and the combined scatterplot is crowded. What analysis would preserve the important information?
  1. Reveal density, inspect sensor-specific curves, and describe the nonlinear patterns.
  2. Reveal density, but treat near-zero correlation as evidence that no relationship remains.
  3. Inspect the sensor groups, but summarize their curved patterns only with linear correlations.
  4. Reveal density, but use only the combined curve to describe the pattern for both sensors.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Two plots are drawn at widths of 6 and 12 inches using the same plot font size, then displayed at the same page width. The second has much smaller labels. What change targets the cause?
  1. Keep both drawing widths and shorten only the second figure’s caption.
  2. Keep both drawing widths and assign different numbered figure labels.
  3. Use a common drawing width and adjust shape with aspect ratio as needed.
  4. Double the second drawing width while retaining the same display width.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

An author needs PDF output but has no TeX distribution installed. What Quarto format uses its included alternative typesetting system?
  1. format: pdf
  2. format: docx
  3. format: typst
  4. format: beamer
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A browser presentation needs a private explanation that the speaker can read while the audience sees only the slide. Where should that explanation go?
  1. Inside a ::: {.notes} div
  2. Inside an ordinary paragraph below the figure
  3. Inside a ::: {.column} div
  4. Inside the plot’s main axis label
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A static dashboard shows nrow(samples) in a box titled "Recorded masses." The table has 180 rows: 14 lack mass, and 9 others lack only lab labels. New measurements later replace the CSV. What count and update procedure fit the box?
  1. Count all 180 sample rows in the stated input, then render again after the CSV changes.
  2. Count 157 rows complete in both fields, then render again after the CSV changes.
  3. Count 166 recorded masses in the stated input, then sort the saved page to import updates.
  4. Count 166 recorded masses in the stated input, then render again after the CSV changes.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A project has freeze: auto and a cached import chunk with no file dependency. Only its CSV changes. A full project render shows old results; a single-document render also shows old results. What action updates both reuse layers?
  1. Clear only chunk caches, then render the full project with unchanged document source.
  2. Render the individual document with --cache-refresh from the updated input.
  3. Render the individual document while retaining its unchanged saved import cache.
  4. Restart R, then render the full project while retaining its frozen computations.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A report for operations staff needs both a quick result and access to the method. Its plot has units and group labels, but the title only says "Measurements" and the prose lists raw means without interpretation. What revision best serves these readers?
  1. Lead with an interpreted finding and a clearer title, but omit all access to code.
  2. Lead with an interpreted finding, improve the title, and include folded code.
  3. Keep the raw means and the title "Measurements," but move included code into folds.
  4. Lead with all analysis code, then give an interpreted finding and a clearer title.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

One source renders North and South reports to distinct output files. Their headings name the right regions, but both display North’s summary. Raw checks show different group means. The unchanged summary chunk is cached. What change makes future variants correct without copying the source?
  1. Track the region parameter in the summary cache key or leave that calculation uncached.
  2. Change the output names again while retaining the same summary chunk and its cache key.
  3. Parameterize the headings again while retaining the same summary chunk and its cache key.
  4. Restart R before each variant while retaining the same summary chunk and its cache key.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

82 Key Terms, each with its definition

A

Accessible figure
An accessible figure communicates its evidence through readable text, distinguishable marks, and a text alternative without depending only on color.
An accessible figure can label species directly and use alt text to describe the mass comparison.
Alt text
Alt text is a text alternative describing the content or meaning of an image so readers using assistive technology can access its information.
Alt text for a species boxplot can describe which distribution is higher and the size of that difference.
Aspect ratio
An aspect ratio describes a figure's height relative to its width; Quarto's fig-asp uses that proportion to set the drawing shape.
An aspect ratio of 0.618 with a drawing width of 6 inches gives a height of about 3.7 inches.
Association
An association is a pattern in which variables vary together; observational data can show it without establishing a causal effect.
An association between diamond cut and price also needs a check of the size differences among cuts.
Audience
An audience is the group expected to use a report, whose questions and needs guide the selection of evidence, detail, and visible code.
A decision-making audience may need the finding and limits, while collaborators also inspect the method.

B

Bibliography
A bibliography stores source entries used to create formatted citations and a reference list, such as entries in a declared BibTeX file.
A report's bibliography lets a citation key identify a data source without typing the full reference each time.
Binwidth
A binwidth is the size of each histogram interval, expressed in the same measurement units as the numerical variable being plotted.
Changing a mass histogram's binwidth from 100 to 500 g can make small clusters harder to see.
Boxplot
A boxplot summarizes a numerical distribution with its median, quartile box, whiskers, and separate points for possible outliers.
A species boxplot makes the Gentoo median and middle-half mass range easy to compare with Adelie values.

C

Cache invalidation
Cache invalidation marks stored work as no longer reusable after a tracked dependency changes, causing the computation to run again.
A file modification-time key can trigger cache invalidation after new measurements replace the input data.
Caching
Caching stores computation results for reuse when their tracked inputs are unchanged, reducing repeated work in expensive report chunks.
Caching can speed up a report while still needing an explicit dependency on a changing input CSV.
Card
A card is a dashboard container for a plot, table, or text; an output-producing code chunk becomes a card in Quarto's dashboard layout.
A clearly titled card lets readers identify the measurement and groups represented by its plot.
Categorical variable
A categorical variable records membership in a set of groups or labels, such as species, whose frequencies can be counted and compared.
Species is a categorical variable, so a bar chart can compare how many birds belong to each group.
Causation
Causation means that changing one factor produces a change in another, a claim that observational association alone cannot establish.
A price association across diamond cuts leaves size as another explanation before any causation claim is justified.
Cherry-picking
Cherry-picking selects only evidence supporting a preferred account while omitting relevant results that would change a reader's interpretation.
Showing only the combined trend is cherry-picking when known subgroup trends reverse its interpretation.
Chunk label
A chunk label is a unique name for an executable block within a document, helping identify its code, saved results, and possible references.
Copying a chunk label without renaming it can stop rendering even when the copied R code is valid.
Chunk option
A chunk option controls the execution or presentation of an individual code block, including whether code runs and which results appear.
The chunk option echo: false leaves a plot visible while hiding the code that produced it.
Code chunk
A code chunk is an executable block embedded in a document whose code can create objects and produce figures, tables, or other results.
An R code chunk that loads data must appear before the plot chunk that needs those data during rendering.
Code folding
Code folding makes included code collapsible in HTML, allowing readers to open it when they want to inspect the report's method.
Code folding suits collaborators who want optional access to code without seeing it throughout the report.
Combination count
A combination count is the number of observations sharing a particular pair of category values, such as one island and one species.
If 44 sampled birds are Adelie penguins from Biscoe island, the Biscoe–Adelie combination count is 44, whichever total later becomes the denominator.
Coordinate zoom
A coordinate zoom changes the visible plot window while preserving the observations available to calculate the plot's statistical summaries.
A coordinate zoom on histogram counts can expose rare widths without recomputing bins from a reduced dataset.
Correlation coefficient
The correlation coefficient r is a number from −1 to 1 that summarizes the direction and strength of a linear relationship.
A correlation coefficient near zero can miss a strong curve that remains obvious in the scatterplot.
Covariation
Covariation is a tendency for two or more variables to change together in a related pattern across the observations being studied.
Covariation between species and mass appears when the body-mass distributions differ across species.
Cross-reference
A cross-reference points to a numbered figure or table through its label, keeping the reference correct when the document's order changes.
A cross-reference such as @fig-mass becomes a numbered link when the figure has the right label and caption.

D

Dashboard
A dashboard presents several key indicators or views together, usually for quick inspection and monitoring instead of a sequential argument.
A penguin dashboard can put measured counts above a species comparison and a scatterplot of measurements.
Denominator
A denominator is the total used as the base of a proportion; changing that total changes the question answered by the same numerator.
Using a total of 168 or 152 as the denominator gives different proportions for the same 44 birds in one island–species combination.
Density scaling
Density scaling makes the area under each group's distribution curve equal to one, so shape can be compared across unequal group sizes.
When the Adelie sample is larger than other species' samples, density scaling keeps it from dominating a comparison of frequency-polygon shapes.
Dependency
A dependency is an input needed by a computation, such as an upstream object, file, or parameter that can affect the resulting output.
Declaring a dependency on an earlier chunk helps a cached summary respond when that chunk changes.
Distribution
A distribution describes which values a variable takes and how often they occur, including its center, spread, and shape.
A body-mass distribution can contain clusters that become clearer when species are plotted separately.

E

Effect size
An effect size describes how large a difference or relationship is, helping readers judge its meaning beyond an absolute claim of a pattern.
A median body-mass difference of about 1,300 g gives an effect size in the original measurement units.
Embedded resources
Embedded resources are images, scripts, and styles bundled into HTML instead of shared as separate local support files.
Embedded resources preserve local figures when sharing one HTML file, but do not supply live map tiles.
Explanatory plot
An explanatory plot is a selected and polished display designed to communicate a finding clearly to readers of a report or presentation.
An explanatory plot can replace variable names with readable labels and state the finding in its title.
Exploratory data analysis
Exploratory data analysis is a cycle of questions, plots, and transformations used to understand data and discover patterns or problems.
An exploratory data analysis of measurements can move from an overall histogram to comparisons by group.
Exploratory hypothesis
An exploratory hypothesis is a proposed explanation or pattern suggested by examining data that needs further evidence for confirmation.
An exploratory hypothesis about group differences can be checked on new observations collected afterward.

F

Figure caption
A figure caption is text attached to a figure that explains its evidence and helps readers interpret the display in the report.
A figure caption can identify the body-mass comparison and name the data source below the plot.
Finding
A finding is an observed result communicated with its meaning, useful numerical detail, and supporting evidence from the analysis.
A finding about median body mass should give the groups, difference or values, and measurement unit.
Freezing
Freezing reuses saved document computations during a full Quarto project render, with auto rerunning documents whose source changed.
Freezing can retain old results after an external CSV changes unless the affected document is explicitly rebuilt.
Frequency polygon
A frequency polygon joins binned frequencies with lines, making it possible to compare several numerical distributions in one display.
A density-scaled frequency polygon overlays species distributions while accounting for unequal counts.

H

Heatmap
A heatmap represents values with tile colors across a grid, helping readers compare many combinations of categorical variables.
A heatmap of island and species can show zero counts explicitly after absent combinations are added.
Histogram
A histogram displays a numerical distribution by grouping nearby values into intervals and showing their frequencies with adjoining bars.
A histogram with 200 g intervals groups nearby body masses instead of making one bar per exact mass.
HTML output
HTML output is a browser-readable report format that can support links, code folding, and interactive widgets alongside text and static figures.
HTML output with bundled resources is convenient to share, though online map tiles can still require internet.
HTML widget
An HTML widget adds browser-side interaction, such as sorting or tooltips, to an HTML-based report using results prepared during rendering.
An HTML widget can sort a saved table without rerunning R or reading a newly updated input file.

I

Incremental display
Incremental display reveals list items or later slide content progressively, allowing the presenter to control the pace of an explanation.
Incremental display can keep listeners on the current point before the next evidence item is revealed.
Inline code
Inline code embeds an executable expression in prose so its result is inserted into the sentence when the document is rendered.
Inline code can insert a formatted mean into a finding without requiring a manual edit after data change.
Interquartile range
The interquartile range is the third quartile minus the first quartile, measuring the width of the middle half of the ordered data.
Quartiles of 3,550 and 4,750 g give an interquartile range of 1,200 g for recorded penguin masses.

K

knitr
knitr is the R execution engine that runs a document’s code chunks and creates Markdown containing their results before output conversion.
During a report render, knitr creates the calculated tables that Pandoc then places in the final output.

L

Lockfile
A lockfile records a project's package versions so an environment manager such as renv can restore that package setup elsewhere.
The renv lockfile helps collaborators install the recorded versions instead of whichever versions are currently newest.

M

Markdown
Markdown is a plain-text writing syntax that marks headings, lists, emphasis, links, and other structure in the surrounding document prose.
Markdown headings organize a report while backticks identify a function name as literal code in a sentence.
Mean
The mean is the sum of recorded numerical values divided by their count, giving an average that can be pulled toward extreme values.
In a penguin sample with a mean body mass of about 4,202 g, the mean lies above the median of the recorded masses.
Median
The median is the middle value of ordered numerical data, or the average of the two middle values when the count is even.
In a penguin sample with a median recorded mass of 4,050 g, the median locates the center without averaging every mass.
Missing value
A missing value represents unavailable information; in R, NA marks missing data and behaves differently from a recorded zero.
A missing value for sex does not prevent a bird's recorded mass from contributing to a mass summary.
Missingness indicator
A missingness indicator records whether a value is missing, allowing the presence of missing information to be compared across groups.
A sex-missingness indicator lets an analyst count missing records within each species and island.

N

Numerical variable
A numerical variable records a quantity whose values can be used in calculations such as differences and averages, with meaningful measurement units.
Body mass is a numerical variable recorded in grams, so nearby values can be grouped in a histogram.

O

Observation
An observation is a set of measurements made on the same object at the same time, stored as one row in a tidy dataset.
One penguin's species and measurements belong to the same observation in the tidy table.
Outlier
An outlier is an observation unusually far from the surrounding pattern, which may reflect a genuine extreme, an error, or a distinct subgroup.
A very large diamond width is an outlier to inspect before deciding whether its measurement is wrong.
Overplotting
Overplotting occurs when many marks overlap, hiding how many observations occupy the same region and making patterns difficult to read.
Overplotting in a large diamonds scatterplot can be reduced with transparent points or two-dimensional bins.

P

Pandoc
Pandoc is a document converter that turns the Markdown produced during a Quarto render into a chosen output such as HTML or Word.
Pandoc converts the report after R code has produced the figure and table results through knitr.
Parameter
A parameter is an input declared for a report that can change between renders, allowing one source to analyze different groups or periods.
A species parameter can drive both a data filter and the group name displayed in the report heading.
PDF output
PDF output is a fixed-page document suited to printing and stable layout, produced in Quarto through LaTeX or Typst typesetting.
A team can use PDF output for a printed report while reviewing an editable draft in Word.

Q

Quartile
A quartile marks a quarter boundary in ordered numerical data; the first and third quartiles bound the middle half of the values.
When the first and third quartiles of body mass are 3,550 and 4,750 g, their difference is the IQR.
Quarto
Quarto is an open-source publishing system that combines prose and executable analysis to create reports, slides, dashboards, and other outputs.
A Quarto report can regenerate its figures and written numerical results from the same analysis code.

R

Random seed
A random seed sets the starting state for repeatable random operations when the software setup and sequence of random calls are the same.
Setting a random seed before sampling keeps an illustrative sample stable during repeated report renders.
Reference document
A reference document is a Word file whose styles are applied to Quarto's docx output through the reference-doc format option.
An organization's reference document can supply the fonts and heading styles for a generated Word draft.
Relative path
A relative path locates a file from a defined starting folder, allowing the same project layout to work without one user's absolute address.
A relative path such as data/raw.csv works when the input is in the expected folder beside the source.
Rendering
Rendering turns a source document into its chosen output, executing enabled computations and converting their results with the surrounding prose.
Rendering from a fresh R session exposes a report that relies on an object created only in the console.
Reproducibility
Reproducibility means that the same data and code can rebuild the same results, supported by recorded software and explicit analysis steps.
A collaborator checks reproducibility by rebuilding the report from the project's inputs and setup instructions.
Revealjs
Revealjs is Quarto's HTML slide format for browser presentations, supporting features such as progressive lists, notes, and slide columns.
A revealjs presentation can show a finding first and reveal its supporting points during the explanation.

S

Scatterplot
A scatterplot places one point per observation using two numerical coordinates, revealing direction, form, strength, and unusual patterns.
A scatterplot of flipper length and body mass shows a positive relationship among measured penguins.
Section title slide
A section title slide introduces a major part of a presentation and is created by a level-one Markdown heading in Quarto's slide structure.
A section title slide can separate the findings from the later discussion of data limitations.
Sensitivity comparison
A sensitivity comparison checks how an analysis's results change when a consequential choice, such as handling suspect values, changes.
When cleaning replaces suspect widths, comparing results before and after cleaning is a sensitivity comparison for that decision.
Setup chunk
A setup chunk performs shared preparation, such as loading packages and data, before later chunks use those resources in the document.
A hidden setup chunk can create the objects needed for figures without adding its own output to the report.
Simpson's paradox
Simpson's paradox occurs when a relationship in combined data differs from or reverses the relationship within relevant subgroups.
Bill measurements illustrate Simpson's paradox: the combined association is negative but each species' is positive.
Speaker notes
Speaker notes are supporting text for the presenter, stored in a notes div without becoming the main content shown to the audience.
Speaker notes can explain a measurement choice while the slide shows only the figure and main finding.
Standard deviation
The standard deviation measures numerical spread around the mean and can be strongly affected by unusually large or small values.
A set of recorded penguin masses with a mean of about 4,202 g has a standard deviation of about 802 g.

T

Third variable
A third variable is another measured factor that can help explain a relationship or difference observed between the variables being compared.
Diamond size is a third variable to inspect when comparing the price distributions of different cuts.
Two-dimensional binning
Two-dimensional binning groups observations into cells across two numerical axes and displays how many points fall in each cell.
Rectangular two-dimensional binning can reveal crowded regions that look uniformly dark in an opaque scatterplot.

V

Value box
A value box is a dashboard display that highlights one named value, created from a chunk with content: valuebox and an appropriate result.
A value box labeled "Birds with recorded mass" should count nonmissing masses instead of all table rows.
Variable
A variable is a quantity or category measured across observations, such as body mass, species, or the year of measurement.
Body mass is a numerical variable, while species records a category for each measured penguin.
Variation
Variation is the tendency of a variable's values to differ across observations, producing a distribution with its own pattern.
A histogram shows variation in body mass before any comparison between species is made.
Version control
Version control records changes to project files over time, allowing earlier source versions to be inspected and recovered with their history.
Version control can show when a cleaning rule changed and which report source used the previous rule.

W

Whisker
A whisker on a standard boxplot reaches the farthest observation within 1.5 interquartile ranges of the corresponding box edge.
A whisker's endpoint is a recorded measurement and need not equal the calculated 1.5-IQR fence.
Within-group proportion
A within-group proportion divides a category combination's count by the total of its selected group, answering a conditional composition question.
A species proportion within Biscoe uses all sampled Biscoe birds as its denominator, not all Adelie birds.

Y

YAML header
A YAML header is a settings block at the start of a document, bounded by lines of three dashes, containing metadata and output options.
A YAML header can set a report title and choose HTML as the output while leaving the prose below it.

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