Skip to content

How R evaluates code

In chapter 8 you wrote functions with {{ }} and .data[[ ]], and you used two rules without the reasons. This chapter gives the reasons. You learn how R finds a name, when it evaluates an argument, and how dplyr finds a column. Then a surprise in a function of yours has an explanation, and you know where to look.

Part V is about functions that other people use: this chapter, then code from data (chapter 18), then a tested library (chapter 19).

programs/17_1_values_code.R
# Chapter 17: a value and a piece of code. quote() keeps code without running it
library(dplyr)
x <- 1 + 2
x
#> [1] 3
code <- quote(1 + 2)
code
#> 1 + 2
class(code)
#> [1] "call"
eval(code)
#> [1] 3
# A condition as code. eval() can run it inside a data frame
adsl <- pharmaverseadam::adsl |>
filter(SAFFL == "Y")
cond <- quote(AGE > 85)
cond
#> AGE > 85
sum(eval(cond, adsl))
#> [1] 18
# filter() does the same with the code you write: it runs AGE > 85 in adsl
adsl |>
filter(AGE > 85) |>
nrow()
#> [1] 18
  • x <- 1 + 2 runs the code at once. x holds the value 3. The code 1 + 2 is gone.
  • quote(1 + 2) does not run the code. It keeps it as an object of class "call": a piece of code that R can run later. eval() runs it.
  • quote(AGE > 85) keeps a condition. eval(cond, adsl) runs it with the columns of adsl as the names: AGE is the column. 18 subjects of the safety population are older than 85.
  • filter(AGE > 85) gives the same 18. filter() does what eval() did: it takes the code that you wrote and runs it inside the data frame.

This is the key idea of the chapter. Base R evaluates an argument as a value. A dplyr verb takes the code of an argument and evaluates it inside the data. The rest of the chapter follows from these two facts.

An environment is a place where R keeps names and their values. Each function call has its own environment for its arguments and the names it makes. When R needs a name, it looks first in the environment of the function, then in the environment where the function was written, and so on outwards to the packages. This is called scope.

programs/17_2_scope.R
# Chapter 17: where R finds a name. First in the function, then where it was made
cutoff <- 65
is_old <- function(age) {
age >= cutoff # cutoff is not an argument: R looks outside the function
}
is_old(c(60, 70, 85))
#> [1] FALSE TRUE TRUE
cutoff <- 80
is_old(c(60, 70, 85)) # the function did not change, the result did
#> [1] FALSE FALSE TRUE
# Better: every value that the function needs is an argument
is_old2 <- function(age, cutoff = 65) {
age >= cutoff
}
is_old2(c(60, 70, 85))
#> [1] FALSE TRUE TRUE
# A name made inside a function stays inside it
f <- function() {
inside <- "only here"
inside
}
f()
#> [1] "only here"
exists("inside")
#> [1] FALSE
# A name with :: says where to look: no search at all
stats::sd(c(60, 70, 85))
#> [1] 12.58306
  • is_old() uses cutoff, but cutoff is not an argument. R finds it outside the function. When cutoff changes from 65 to 80, the same call gives another result: 70 is no longer “old”.
  • is_old2() takes cutoff as an argument with a default. Its result depends on its arguments only. Write every function this way: a function that reads a value from outside is a trap for the next programmer.
  • inside is made inside f(). After the call, it is gone: exists("inside") is FALSE. A function cannot leave work objects behind.
  • stats::sd names the package. R then does not search: it takes sd from stats. library() adds a package to the list of places that R searches, so two packages can both have a filter(). :: removes the doubt.

When you run a program at the console, the names of its top level go to the global environment, the outermost environment of your session.

R evaluates an argument only when the body of the function first uses it. This is called lazy evaluation.

programs/17_3_lazy.R
# Chapter 17: lazy evaluation. R evaluates an argument when the body first uses it
show_order <- function(x) {
cat("1. the function starts\n")
value <- x
cat("3. the function has x\n")
value
}
show_order({
cat("2. now R evaluates x\n")
5
})
#> 1. the function starts
#> 2. now R evaluates x
#> 3. the function has x
#> [1] 5
# An argument that the body never uses is never evaluated
first_only <- function(a, b) {
a * 2
}
first_only(10, stop("this is never evaluated"))
#> [1] 20
# A default can use another argument: R evaluates it when it is needed
pct <- function(n, total = sum(n)) {
round(100 * n / total, 1)
}
pct(c(86, 84, 84))
#> [1] 33.9 33.1 33.1
pct(c(86, 84, 84), total = 306)
#> [1] 28.1 27.5 27.5
  • The numbered lines show the order. The function starts (1). Only when the body reads x does R evaluate the code of the argument (2). Then the function goes on (3).
  • first_only() never uses b, so stop() never runs, and there is no error.
  • The default total = sum(n) uses another argument. R evaluates it when the body needs total, so it can use n. With total = 306, the same counts become percents of all 306 subjects of DM.

Lazy evaluation is what lets dplyr take your code: the argument AGE > 85 is not evaluated when filter() starts. filter() gets the code, and evaluates it itself, inside the data.

17.4 Data masking: why AGE works without quotes

Section titled “17.4 Data masking: why AGE works without quotes”

In base R, AGE alone is an error: there is no object AGE. Inside filter() it works. dplyr puts the columns of the data frame in front of the environment of your program. A column then hides a variable with the same name. This is called data masking.

programs/17_4_masking.R
# Chapter 17: data masking. dplyr looks for a name in the data first
library(dplyr)
adsl <- pharmaverseadam::adsl |>
filter(SAFFL == "Y")
# AGE is a column of adsl
adsl |> filter(AGE > 85) |> nrow()
#> [1] 18
# limit is not a column: dplyr then looks in the program
limit <- 85
adsl |> filter(AGE > limit) |> nrow()
#> [1] 18
# The trap: a variable with the same name as a column. The column wins
SEX <- "F"
adsl |> filter(SEX == SEX) |> nrow()
#> [1] 254
# The pronouns say where to look: .data is the data, .env is the program
adsl |> filter(.data$SEX == .env$SEX) |> nrow()
#> [1] 143
  • AGE is a column, so dplyr finds it in the data.
  • limit is not a column. dplyr does not find it in the data, so it looks in the program and finds 85. The result is the same 18 subjects.
  • SEX <- "F" makes a variable with the name of a column. In filter(SEX == SEX), both names are the column, because the data comes first. Every row is equal to itself, and all 254 rows stay. No error and no warning: a silent wrong result.
  • .data$SEX is the column, .env$SEX is the variable of the program. With the two pronouns, the filter keeps the 143 women.
You write dplyr looks Use it when
SEX the data first, then the program the usual case
.data$SEX or .data[["SEX"]] the data only the name is in a text, or it must be a column
.env$SEX the program only a variable could have the name of a column

A function argument is outside the data. When a function passes a column name to a dplyr verb, the verb must get the code of the argument, not its value. {{ }} does this (chapter 8).

programs/17_5_embrace.R
# Chapter 17: {{ }} passes the code of an argument on. enquo() and !! are its two halves
library(dplyr)
adsl <- pharmaverseadam::adsl |>
filter(SAFFL == "Y")
mean_by <- function(data, var, by) {
data |>
summarise(n = n(), mean = round(mean({{ var }}), 1), .by = {{ by }})
}
mean_by(adsl, AGE, ARM)
#> # A tibble: 3 x 3
#> ARM n mean
#> <chr> <int> <dbl>
#> 1 Placebo 86 75.2
#> 2 Xanomeline High Dose 84 74.4
#> 3 Xanomeline Low Dose 84 75.7
# The same in two steps: enquo() keeps the code, !! puts it in
mean_by2 <- function(data, var, by) {
var <- rlang::enquo(var)
by <- rlang::enquo(by)
cat("Mean of", rlang::as_label(var), "by", rlang::as_label(by), "\n")
data |>
summarise(n = n(), mean = round(mean(!!var), 1), .by = !!by)
}
mean_by2(adsl, AGE, SEX)
#> Mean of AGE by SEX
#> # A tibble: 2 x 3
#> SEX n mean
#> <chr> <int> <dbl>
#> 1 F 143 75.7
#> 2 M 111 74.4
# The caller can give code, not only a name
mean_by(adsl, AGE * 12, SEX)
#> # A tibble: 2 x 3
#> SEX n mean
#> <chr> <int> <dbl>
#> 1 F 143 908.
#> 2 M 111 892.

{{ var }} has two halves, and mean_by2() writes them out:

  • rlang::enquo(var) captures the code of the argument, here AGE, with the environment of the caller. The result is a quosure: code plus the place to evaluate it.
  • !!var puts that code into the verb. !! is pronounced “bang bang”.
  • rlang::as_label() turns the code into a text, for a title or a message: “Mean of AGE by SEX”.

You need the two halves only when you want the code itself, as here for the title. For everything else, {{ }} is shorter. The last call shows that the caller can give code, not only a name: AGE * 12 is the age in months.

The mean ages per planned arm, 75.2, 74.4 and 75.7, are those of program 01_4 in chapter 1.

A name can be built from other names and values, in two ways.

programs/17_6_names.R
# Chapter 17: build column names. across() with .names, and := with a glue string
library(dplyr)
adsl <- pharmaverseadam::adsl |>
filter(SAFFL == "Y")
# .names is a pattern: {.col} is the column, {.fn} the name of the function
funs <- list(
mean = \(x) round(mean(x, na.rm = TRUE), 1),
max = \(x) max(x, na.rm = TRUE)
)
adsl |>
summarise(
across(c(AGE, TRTDURD), funs, .names = "{.col}_{.fn}"),
.by = ARM
)
#> # A tibble: 3 x 5
#> ARM AGE_mean AGE_max TRTDURD_mean TRTDURD_max
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 Placebo 75.2 89 150. 210
#> 2 Xanomeline High Dose 74.4 88 98.2 200
#> 3 Xanomeline Low Dose 75.7 88 97.3 212
# := lets the left side be a glue string: {{ var }} is the name, {limit} a value
flag_over <- function(data, var, limit) {
data |>
mutate("{{ var }}_GT{limit}" := if_else({{ var }} > limit, "Y", "N"))
}
adsl |>
flag_over(AGE, 80) |>
count(AGE_GT80)
#> # A tibble: 2 x 2
#> AGE_GT80 n
#> <chr> <int>
#> 1 N 177
#> 2 Y 77
# A name in a text works the same way
new <- "SAFFL2"
adsl |>
mutate("{new}" := SAFFL) |>
select(USUBJID, SAFFL, SAFFL2) |>
head(2)
#> # A tibble: 2 x 3
#> USUBJID SAFFL SAFFL2
#> <chr> <chr> <chr>
#> 1 01-701-1015 Y Y
#> 2 01-701-1023 Y Y
  • across() applies a list of functions to a set of columns (chapter 7). .names = "{.col}_{.fn}" is a pattern for the new names: {.col} is the column, {.fn} the name of the function in the list. So AGE with mean becomes AGE_mean.
  • := lets the left side of mutate() or summarise() be a glue string: a text with { } in it. "{{ var }}_GT{limit}" puts in the name of the argument (AGE) and the value of limit (80). The new column is AGE_GT80: 77 subjects are older than 80.
  • "{new}" := takes the name from a text variable.

= cannot do this: the left side of = is always a plain name. Use := when the name is built.

A value in R is never read as code. So a quote, an &, a ; or a % inside a text needs no protection.

programs/17_7_no_quoting.R
# Chapter 17: a value is never code. Quotes, & and ; in a value need no protection
library(dplyr)
site <- "O'Brien Clinic"
dept <- "R&D"
note <- "Smith & Jones; 50% done"
paste0("Site: ", site, " (", dept, ")")
#> [1] "Site: O'Brien Clinic (R&D)"
nchar(note)
#> [1] 23
# glue fills {name} with the value. Braces inside the value stay text
glue::glue("Footnote: {note}")
#> Footnote: Smith & Jones; 50% done
value <- "{AGE}"
glue::glue("The value is {value}")
#> The value is {AGE}
# A value from the data goes into filter() as it is
arm <- "Xanomeline High Dose"
pharmaverseadam::adsl |>
filter(ARM == arm) |>
nrow()
#> [1] 84
  • "O'Brien Clinic" has a single quote inside double quotes. It is one more character of the text.
  • "Smith & Jones; 50% done" has 23 characters. The &, the ; and the % are text.
  • glue::glue() fills {note} with the value of note. It reads the braces of the template only: the value "{AGE}" stays the text {AGE}.
  • filter(ARM == arm) compares the column with the value: 84 subjects in the high dose arm. Any text can go there.
programs/17_8_traps.R
# Chapter 17: two common traps of data masking
library(dplyr)
adsl <- pharmaverseadam::adsl |>
filter(SAFFL == "Y")
# Trap 1: an argument with the name of a column. ARM == ARM is always TRUE
count_arm <- function(data, ARM) {
data |> filter(ARM == ARM) |> nrow()
}
count_arm(adsl, "Placebo")
#> [1] 254
# The fix: .env$ARM is the argument, not the column
count_arm <- function(data, ARM) {
data |> filter(.data$ARM == .env$ARM) |> nrow()
}
count_arm(adsl, "Placebo")
#> [1] 86
# Trap 2: a text where {{ }} expects a name. mean("AGE") is not a mean
mean_of <- function(data, var) {
data |> summarise(mean = mean({{ var }}))
}
mean_of(adsl, "AGE")
#> Warning:
#> There was 1 warning in `summarise()`.
#> i In argument: `mean = mean("AGE")`.
#> Caused by warning in `mean.default()`:
#> ! argument is not numeric or logical: returning NA
#> # A tibble: 1 x 1
#> mean
#> <dbl>
#> 1 NA

Trap 1: an argument with the name of a column. count_arm(adsl, "Placebo") gives 254, not 86. Inside filter(), ARM is the column, both times: data masking again. .env$ARM is the argument, and the count is right: 86. A better fix is an argument name that no data set has, such as arm_sel.

Trap 2: a text where {{ }} expects a name. mean_of(adsl, "AGE") passes the text "AGE". mean("AGE") is the mean of a text: R gives a warning and NA. A name in a text needs .data[[var]] (chapter 8).

More traps that come from the same rules:

What you see The cause The fix
a filter keeps all rows a variable with the name of a column .env$name, or another name
Column var is not found a column argument without {{ }} {{ var }}
a mean is NA, argument is not numeric a text passed to {{ }} .data[[var]]
a function gives another result after a change outside it the function reads a variable that is not an argument make it an argument
  • A value is a result; code is kept with quote() and run with eval(). A dplyr verb takes the code of its arguments and runs it inside the data.
  • R finds a name in the function first, then where the function was written, then in the packages. :: names the package.
  • An argument is evaluated when the body first uses it (lazy evaluation).
  • Data masking: inside a dplyr verb, a column hides a variable with the same name. .data$ is the data, .env$ the program.
  • {{ }} passes the code of an argument on. enquo() captures it, !! puts it in, as_label() makes it a text.
  • across(.names = ) and := with a glue string build column names.
  • A value is never code, so R needs no macro quoting.

Exercise 17-1. What does f(1) give for f <- function(a, b = a * 2) { a <- 10; b }? Why? What changes when you add force(b) as the first line of the body?

Exercise 17-2. In the ALT rows of pharmaverseadam::adlb (with a value, without DTYPE), set ANRHI <- 40 in your program. How many rows does filter(AVAL > ANRHI) keep, and how many does filter(AVAL > .env$ANRHI) keep? Why do they differ?

Exercise 17-3. Write n_over(data, var, limit, by). It counts the subjects with var > limit per group, in a column named n_<var>_over_<limit>. How many subjects of each arm are older than 80?

Exercise 17-4. Write mean_of() of program 17_8 again, so that mean_of(adsl, "AGE") works. Find two ways.

The answers are in Answers, Parts IV and V.

Found an error or have a question? Write to datastep.studio@gmail.com· Every program runs in DataStep Studio for R, the R extension for VS Code and Positron.

Data: the CDISC pilot study (cdiscpilot01), from the R packagespharmaversesdtm andpharmaverseadam (Apache License 2.0).

R is a project of the R Foundation. SAS and all other SAS Institute Inc. product or service names are registered trademarks or trademarks of SAS Institute Inc. This book is not affiliated with or endorsed by SAS Institute Inc. or the R Foundation. CDISC, SDTM and ADaM are trademarks of the Clinical Data Interchange Standards Consortium.

© 2026 DataStep Labs. All rights reserved.