R Quote and Substitute
quote() holds code as data instead of running it. substitute() captures the code a caller wrote, and deparse() turns held code back into text.
Hold code with quote
quote() stores the expression total + tax as data. print() shows the code itself, and class() shows the held value is a call.
q <- quote(total + tax)
print(q)
print(class(q))Turn held code back into text
deparse() takes a quoted expression and returns it as a character string. The string holds the same code that quote() stored.
held <- quote(score * 2)
print(held)
print(deparse(held))Capture what a caller wrote
substitute() inside show_expr reads the expression passed for col. deparse() turns that captured expression into the string that prints.
show_expr <- function(col) {
deparse(substitute(col))
}
print(show_expr(score + bonus))Each call is captured as written
capture() runs twice with two different arguments. Each print shows the exact expression from its own call.
capture <- function(value) {
deparse(substitute(value))
}
print(capture(total_score))
print(capture(price * count))Example
report <- function(item) {
deparse(substitute(item))
}
task <- quote(units * price + fee)
print(task)
print(class(task))
print(deparse(task))
print(report(units * price + fee))Key points
- quote() returns its code as data and does not run it.
- A quoted expression prints as the code itself.
- The class of a quoted expression is call.
- substitute() inside a function captures the expression a caller passed for an argument.
- deparse() turns held code back into a character string.
- The captured text holds the caller's own names and operators.
In this example, quote() first holds units * price + fee as a call. deparse() turns the held call into text, and report() captures the same expression straight from its caller.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does print(class(quote(score + bonus))) show?