Introduction to code chunks

Introduction

In a Quarto document, code chunks are self-contained blocks of executable code embedded within the text. Each chunk is delimited by a fenced syntax (triple backticks followed by a language label, such as {r}) telling Quarto which language engine to use. When you render the document, Quarto runs each chunk, captures its output, such as console text, tables and plots, and inserts that output directly into the document at the chunk’s position.

Chunks aren’t limited to R: a single document can mix chunks written in R, Python, Julia, or other supported languages.

Chunks Share One Session

Do: Carefully look at the three chunks below that all use R in a different way.

First chunk:

# Create a small dataset
set.seed(123)
data <- data.frame(
  group = rep(c("A", "B"), each = 10),
  score = c(rnorm(10, mean = 75, sd = 5),
            rnorm(10, mean = 82, sd = 6))
)

# Display a quick summary of the data
summary(data$score)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  68.67   73.58   78.91   79.31   84.22   92.72 

Second chunk:

# Use the dataset created in the previous chunk
model <- lm(score ~ group, data = data)

# Display regression results
summary(model)

Call:
lm(formula = score ~ group, data = data)

Residuals:
     Min       1Q   Median       3Q      Max 
-13.0514  -3.3335   0.1264   2.1877   9.4697 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)   75.373      1.754  42.970  < 2e-16 ***
groupB         7.879      2.481   3.176  0.00523 ** 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 5.547 on 18 degrees of freedom
Multiple R-squared:  0.3591,    Adjusted R-squared:  0.3235 
F-statistic: 10.09 on 1 and 18 DF,  p-value: 0.005231

Third chunk:

Distribution of scores by group.

See: As you can see, an object created in the first chunk is still available by the time the second or third chunk runs. For example, data and model are both still available in the third chunk, even though neither was created here. All R chunks in a document run in the same, shared session, so objects created in one chunk persist and can be reused in any chunk that comes after it, much like running code line by line in a single R script.

This has a practical consequence: chunks are not independent snippets to be formatted individually. They are steps in one continuous computation, executed top to bottom.

Common Mistake

Because chunks share a session, code that runs fine when you execute chunks one at a time in RStudio can still fail on a full render if an earlier chunk was skipped, reordered, or edited since you last ran it. Rendering the whole document from a clean session, covered next, is the only way to be sure every chunk still works in the order it actually appears.

Practice Exercise

In the editor below, write two short pieces of code to mimic how two chunks in the same document would behave.

  1. First, create a numeric vector called temperatures containing a few values of your choice.
  2. Then, on a new line, compute the mean of temperatures.

Run both lines together and confirm that the second line can access the object created by the first.

# "Chunk" 1: create an object
temperatures <- c(18, 21, 19, 23, 17)

# "Chunk" 2: reuse the object created above
mean(temperatures)
[1] 19.6

Running these two steps in sequence in the same session mirrors what happens across two chunks in a real Quarto document: temperatures is created in the first step and is still available in the second, without being redefined.

Back to top