Guru's Verification engine ensures consistency, confidence, and trust in the knowledge your organization shares. Learn more.

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` statementbar <- 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:

You must have Author or Collection Owner permission to create Guru Cards. Contact your team's Guru admins to use this template.