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

R Functions as Values

A function is a value that can travel like any other value. A function can arrive as an argument and be called by that argument name.

Call a function that arrived as an argument

apply_rule takes a value and a rule. The rule arrives as an argument and runs by that name.

apply_rule <- function(value, rule) {
  rule(value)
}
print(apply_rule(16, sqrt))
print(apply_rule(3.14159, round))

One call site, many rules

report hands its values to whichever rule arrives. max, min and length each answer through the same line of code.

report <- function(values, rule) {
  cat("Result:", rule(values), "\n")
}
scores <- c(70, 85, 90)
report(scores, max)
report(scores, min)
report(scores, length)

Run a call built from a list

do.call takes a function and a list of arguments. It runs the function as if the list items were written in the call.

args <- list(4, 8, 15)
print(do.call(sum, args))
words <- list("red", "green", "blue")
print(do.call(paste, words))

Example

ana <- data.frame(name = "Ana", score = 90)
bo <- data.frame(name = "Bo", score = 75)
cy <- data.frame(name = "Cy", score = 82)
frames <- list(ana, bo, cy)
print(do.call(rbind, frames))

Key points

  • A function name without brackets stands for the function itself.
  • Passing sqrt as an argument hands the function to the receiving function.
  • The receiving function calls the argument by its own name.
  • do.call() runs a function with arguments packed in a list.
  • do.call(rbind, frames) stacks a list of frames into one frame.

In this example three small frames sit in one list. do.call(rbind, frames) stacks them into a single frame, and the rows keep the order of the list.

Note

do.call() takes the function first and the list of arguments second.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does do.call(sum, list(4, 8, 15)) print?