- Learn
- Computer Science & IT
- Data Science & AI
- Data Analysis with R
- Exploratory Analysis in R
Exploratory Analysis in R: Reporting with Quarto
IntermediateLesson 7 of 7 in Data Analysis with R Course
What you will learn
- 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 questionsTreat 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 variesChoose 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 valuesSpot 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.
- Plan an exploratory analysis around questions
- 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 categoriesCompare distributions between groups with boxplots, density-scaled frequency polygons and reordered categories, and recognize when a third variable distorts the comparison.
- Explore two categorical variablesCount 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 patternsPlot two numerical variables without overplotting, describe the direction, form and strength of the relationship, and check whether subgroups or other variables change the picture.
- Compare a numerical variable across categories
- 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 documentRecognize 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 codeUse 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 citationsSize and caption plots, present summary tables, refer to figures and tables by number, and cite sources from a bibliography file.
- Build and render a Quarto document
- 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 WordSet 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 slidesTurn 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 dashboardLay 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.
- Render documents to HTML, PDF and Word
- 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-renderOrganize 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 cachingDeclare 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.
- Make a report that anyone can re-render
- 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 readersChoose 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 honestlyWord conclusions so they match what exploratory data can support, report the data's limits and the choices you made, and avoid presentations that mislead.
- Plan and write a report for its readers
Exploratory Analysis in R study guide
1Explore 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 = TRUEwhen 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
NAwhile 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.
2Explore 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.
3Write 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 . 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
.qmdfor 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.
| Option | Runs code? | Shows code? | Shows results? |
|---|---|---|---|
eval: false | No | Yes | No new results |
include: false | Yes | No | No |
echo: false | Yes | No | Yes |
output: false | Yes | Yes | No |
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.
4Choose 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
| Format | Useful for | Main setup or sharing issue |
|---|---|---|
| HTML | Reading on screen and browser interaction | Include supporting resources when sharing |
| PDF through LaTeX | Printing and fixed pages | Install a TeX distribution |
| PDF through Typst | Fixed pages with Typst typesetting | Select format: typst |
Word (docx) | Editing and comments | Use 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, orbeamerfor 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.
5Keep 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-refreshto force cached work to rerun. - Project freezing and chunk caching control different kinds of reuse.
6Communicate 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
1Start an exploration and inspect its data
12 steps
- 1IntroductionMove 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.
- 2ExampleInspect 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.
- 3ExplanationName 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.
- 4ChallengeRefine 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.
- 5ExampleBuild 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.
- 6ExampleAttach 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.
- 7ChallengeChoose 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.
- 8ExampleFind 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.
- 9TipPreserve 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.
- 10ExplanationInvestigate 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.
- 11ChallengeKeep 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.
- 12RecapKeep 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.
2Compare distributions and uncover hidden patterns
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionChoose a relationship view
- 2ExampleRead the species boxplots
- 3ExplanationDistinguish fences from whiskers
- 4Key InsightSeparate shape from sample size
- 5ChallengeInvestigate a surprising group gap
- 6ExampleCount and complete the grid
- 7ExampleAnswer the within-island question
- 8ChallengeReverse the conditioning group
- 9ExampleDescribe a numerical pair
- 10TipReveal crowded regions
- 11ExampleInspect the bill relationship by species
- 12ChallengeExplain a reversal without a causal claim
- 13ChallengePlan a fair combined investigation
- 14RecapRead what a summary leaves out
3Build a report that renders on its own
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionKeep explanation beside computation
- 2ExampleStart with a header and setup
- 3ExplanationRun the complete source
- 4ChallengeRepair a hidden dependency
- 5ExampleHide setup, preserve its work
- 6ExampleShow a result without its code
- 7ExampleInsert a formatted number
- 8ChallengeKeep a plot visible
- 9ExampleName and describe the figure
- 10ExampleFormat a table and identify its sources
- 11ChallengeRepair a figure reference
- 12ChallengeCheck one complete evidence chain
- 13RecapCheck source, execution, and presentation
4Choose the right report, slides, or dashboard
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionStart with the reader’s task
- 2ExplanationMatch the document format
- 3TipShare the resources the report needs
- 4ChallengeChoose an editable draft
- 5ExampleLay out the talk’s argument
- 6TipPreserve detail without overcrowding
- 7ChallengeImprove an overflowing slide
- 8ExampleArrange the dashboard
- 9ExampleName one value precisely
- 10ChallengeRefresh a static page
- 11ChallengeChoose outputs for two uses
- 12RecapInspect the final form
5Rebuild and reuse a report safely
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionPreserve the path from inputs to results
- 2ExampleMake the project portable
- 3ExplanationRecord the software and random state
- 4ChallengeTest a fresh start
- 5ExampleUse one input in data and text
- 6ExampleRender separate variants
- 7ExplanationTrack what a cached result depends on
- 8ChallengeFind the stale import
- 9Key InsightDistinguish two reuse layers
- 10ChallengeRebuild after an external update
- 11RecapMake dependencies visible
6Turn exploration into a clear, honest report
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAnswer the reader’s question
- 2ExplanationChoose the evidence readers need
- 3ExampleWrite a finding with units
- 4TipMake the figure accessible
- 5ChallengeRevise a reader-facing display
- 6ExplanationSeparate an observation from a cause
- 7ExampleDescribe the data and the decisions
- 8ChallengeRepair a claim about generality
- 9ChallengeAudit the final presentation
- 10RecapGive readers a fair account
Exploratory Analysis in R practice questions
Set 1: Read data and build a report10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
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
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
cleaned, created only in the R console. Its plot runs interactively but rendering says the object is missing. What change addresses the cause?Show answerHide answer
cleaned before the plot uses it. Hiding code changes presentation, not the existence of objects during execution.Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
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
Show answerHide answer
Set 2: Control output and inspect relationships10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
label: fig-growth and fig-cap: "Growth over time". What text inserts its numbered reference into a sentence?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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?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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
drop_na() for a mass-only summary. No other fields are missing. How many usable mass records are lost unnecessarily?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
na.rm = TRUE. What count should accompany that median as its measured sample size?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
embed-resources: true accomplish?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Diagnose reports before sharing10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
.md. What source change enables executable Quarto content?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
renv.lock and wants the package versions it records. What renv command performs that setup?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Combine analysis, execution, and communication10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Accessible figure
Alt text
Aspect ratio
fig-asp uses that proportion to set the drawing shape.Association
Audience
B
Bibliography
Binwidth
Boxplot
C
Cache invalidation
Caching
Card
Categorical variable
Causation
Cherry-picking
Chunk label
Chunk option
echo: false leaves a plot visible while hiding the code that produced it.Code chunk
Code folding
Combination count
Coordinate zoom
Correlation coefficient
Covariation
Cross-reference
@fig-mass becomes a numbered link when the figure has the right label and caption.D
Dashboard
Denominator
Density scaling
Dependency
Distribution
E
Effect size
Embedded resources
Explanatory plot
Exploratory data analysis
Exploratory hypothesis
F
Figure caption
Finding
Freezing
auto rerunning documents whose source changed.Frequency polygon
H
Heatmap
Histogram
HTML output
HTML widget
I
Incremental display
Inline code
Interquartile range
K
knitr
L
Lockfile
M
Markdown
Mean
Median
Missing value
NA marks missing data and behaves differently from a recorded zero.Missingness indicator
N
Numerical variable
O
Observation
Outlier
Overplotting
P
Pandoc
Parameter
PDF output
Q
Quartile
Quarto
R
Random seed
Reference document
docx output through the reference-doc format option.Relative path
data/raw.csv works when the input is in the expected folder beside the source.Rendering
Reproducibility
Revealjs
S
Scatterplot
Section title slide
Sensitivity comparison
Setup chunk
Simpson's paradox
Speaker notes
Standard deviation
T
Third variable
Two-dimensional binning
V
Value box
content: valuebox and an appropriate result.Variable
Variation
Version control
W
Whisker
Within-group proportion
Y
YAML header
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.