R | Lazy Evaluation
Function arguments in R are lazily evaluated [2], which means that the expressions passed to arguments are not evaluated until they actually appear in the body of the function. This is a powerful mechanism for reducing the amount of computation required as well as for metaprogramming, but it does lead to some potentially non-intuitive behaviors if not accounted for.
Examples:
foo <- function(x) {
print("this happened")
return(x)
}
foo(stop()) # WILL print, because `x` is not evaluated until the `return` statement
bar <- function(x) {
x
print("this happened")
return(x)
}
bar(stop()) # will NOT print because `stop()` is evaluated before the `print` statement
# you can even
baz <- function(x) {
print("yup still works")
}
baz(this(aint(evaluated))) # will still print as long as the argument is a legal form
Resources: