๐ŸŽ“ A1Learner
๐Ÿ”
0 of 27 lessons completed

R Delayed Assignment

Delayed assignment binds a name to an expression that has not run yet. The expression runs the first time the value is used.

Nothing runs until the first use

delayedAssign binds answer to a block that prints a line and gives 42. The not yet line prints first, because the block runs only when answer is printed.

delayedAssign("answer", {
  cat("working it out\n")
  c(42)
})
cat("not yet\n")
print(answer)

The value is kept

answer is printed twice here. The working out line appears once, and the second print shows the kept value of 42 alone.

delayedAssign("answer", {
  cat("working it out\n")
  c(42)
})
cat("not yet\n")
print(answer)
print(answer)

An unused delayed value never runs

Two names are bound with delayedAssign. Only used is printed, so only its building line appears.

delayedAssign("used", {
  cat("building used\n")
  c(5)
})
delayedAssign("unused", {
  cat("building unused\n")
  c(9)
})
print(used)

A delayed value inside a sum

total is bound to a block that gives 20. Adding 5 forces the block to run once, and the later print shows the kept total.

delayedAssign("total", {
  cat("adding up\n")
  c(20)
})
print(total + 5)
print(total)

Example

delayedAssign("discount", {
  cat("working out the discount\n")
  c(15)
})
price <- 100
cat("price ready\n")
print(price - discount)
print(discount)

Key points

  • delayedAssign() takes a name as text and an expression to hold back.
  • Lines before the first use print before the working out starts.
  • The first use runs the held back expression once.
  • The worked out value is kept after the first use.
  • Later uses show the kept value with no fresh working out.
  • A delayed value that is never used never runs its expression.

In this example, discount stays unworked while the price line prints. Taking the discount from the price runs its block once, giving 85, and the last print shows the kept discount of 15.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

A name is bound with delayedAssign() and its value is printed twice. How many times does its expression run?