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).
17.1 A value and a piece of code
Section titled “17.1 A value and a piece of code”# Chapter 17: a value and a piece of code. quote() keeps code without running itlibrary(dplyr)
x <- 1 + 2x#> [1] 3
code <- quote(1 + 2)code#> 1 + 2class(code)#> [1] "call"eval(code)#> [1] 3
# A condition as code. eval() can run it inside a data frameadsl <- pharmaverseadam::adsl |> filter(SAFFL == "Y")cond <- quote(AGE > 85)cond#> AGE > 85sum(eval(cond, adsl))#> [1] 18
# filter() does the same with the code you write: it runs AGE > 85 in adsladsl |> filter(AGE > 85) |> nrow()#> [1] 18x <- 1 + 2runs the code at once.xholds the value 3. The code1 + 2is 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 ofadslas the names:AGEis the column. 18 subjects of the safety population are older than 85.filter(AGE > 85)gives the same 18.filter()does whateval()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.
17.2 Where R finds a name
Section titled “17.2 Where R finds a name”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.
# Chapter 17: where R finds a name. First in the function, then where it was madecutoff <- 65is_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 <- 80is_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 argumentis_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 itf <- function() { inside <- "only here" inside}f()#> [1] "only here"exists("inside")#> [1] FALSE
# A name with :: says where to look: no search at allstats::sd(c(60, 70, 85))#> [1] 12.58306is_old()usescutoff, butcutoffis not an argument. R finds it outside the function. Whencutoffchanges from 65 to 80, the same call gives another result: 70 is no longer “old”.is_old2()takescutoffas 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.insideis made insidef(). After the call, it is gone:exists("inside")isFALSE. A function cannot leave work objects behind.stats::sdnames the package. R then does not search: it takessdfromstats.library()adds a package to the list of places that R searches, so two packages can both have afilter().::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.
17.3 Lazy evaluation of arguments
Section titled “17.3 Lazy evaluation of arguments”R evaluates an argument only when the body of the function first uses it. This is called lazy evaluation.
# Chapter 17: lazy evaluation. R evaluates an argument when the body first uses itshow_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 evaluatedfirst_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 neededpct <- function(n, total = sum(n)) { round(100 * n / total, 1)}pct(c(86, 84, 84))#> [1] 33.9 33.1 33.1pct(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
xdoes R evaluate the code of the argument (2). Then the function goes on (3). first_only()never usesb, sostop()never runs, and there is no error.- The default
total = sum(n)uses another argument. R evaluates it when the body needstotal, so it can usen. Withtotal = 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.
# Chapter 17: data masking. dplyr looks for a name in the data firstlibrary(dplyr)
adsl <- pharmaverseadam::adsl |> filter(SAFFL == "Y")
# AGE is a column of adsladsl |> filter(AGE > 85) |> nrow()#> [1] 18
# limit is not a column: dplyr then looks in the programlimit <- 85adsl |> filter(AGE > limit) |> nrow()#> [1] 18
# The trap: a variable with the same name as a column. The column winsSEX <- "F"adsl |> filter(SEX == SEX) |> nrow()#> [1] 254
# The pronouns say where to look: .data is the data, .env is the programadsl |> filter(.data$SEX == .env$SEX) |> nrow()#> [1] 143AGEis a column, so dplyr finds it in the data.limitis 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. Infilter(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$SEXis the column,.env$SEXis 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 |
17.5 Pass code on: embracing and enquo()
Section titled “17.5 Pass code on: embracing and enquo()”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).
# Chapter 17: {{ }} passes the code of an argument on. enquo() and !! are its two halveslibrary(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 inmean_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 namemean_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, hereAGE, with the environment of the caller. The result is a quosure: code plus the place to evaluate it.!!varputs 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.
17.6 Build column names
Section titled “17.6 Build column names”A name can be built from other names and values, in two ways.
# Chapter 17: build column names. across() with .names, and := with a glue stringlibrary(dplyr)
adsl <- pharmaverseadam::adsl |> filter(SAFFL == "Y")
# .names is a pattern: {.col} is the column, {.fn} the name of the functionfuns <- 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 valueflag_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 waynew <- "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 Yacross()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. SoAGEwithmeanbecomesAGE_mean.:=lets the left side ofmutate()orsummarise()be a glue string: a text with{ }in it."{{ var }}_GT{limit}"puts in the name of the argument (AGE) and the value oflimit(80). The new column isAGE_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.
17.7 Why R needs no macro quoting
Section titled “17.7 Why R needs no macro quoting”A value in R is never read as code. So a quote, an &, a ; or a % inside a text needs no protection.
# Chapter 17: a value is never code. Quotes, & and ; in a value need no protectionlibrary(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 textglue::glue("Footnote: {note}")#> Footnote: Smith & Jones; 50% donevalue <- "{AGE}"glue::glue("The value is {value}")#> The value is {AGE}
# A value from the data goes into filter() as it isarm <- "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 ofnote. 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.
17.8 Common traps
Section titled “17.8 Common traps”# Chapter 17: two common traps of data maskinglibrary(dplyr)
adsl <- pharmaverseadam::adsl |> filter(SAFFL == "Y")
# Trap 1: an argument with the name of a column. ARM == ARM is always TRUEcount_arm <- function(data, ARM) { data |> filter(ARM == ARM) |> nrow()}count_arm(adsl, "Placebo")#> [1] 254
# The fix: .env$ARM is the argument, not the columncount_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 meanmean_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 NATrap 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 |
17.9 Summary
Section titled “17.9 Summary”- A value is a result; code is kept with
quote()and run witheval(). 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.
17.10 Exercises
Section titled “17.10 Exercises”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.