Menu
Coddy logo textTech

Anonymous Functions

Part of the Logic & Flow section of Coddy's R journey. Lesson 27 of 64.

In R a function is a value like a number or a string. function(x) x * 2 creates a function without giving it a name, and the value of its last expression is what it returns:

double <- function(x) x * 2
print(double(21))
print((function(x) x + 1)(9))

Output:

[1] 42
[1] 10

R 4.1 added a short form: \(x) means the same as function(x). Use braces when the body needs several lines:

square <- \(x) x^2
label <- function(x) {
  size <- if (x > 10) "big" else "small"
  paste(x, "is", size)
}
print(square(4))
print(label(12))

Output:

[1] 16
[1] "12 is big"

Because functions are values, a list can hold several of them under names. ops[["inc"]] is a function, so ops[["inc"]](5) calls it:

ops <- list(inc = \(x) x + 1, neg = \(x) -x)
print(ops[["inc"]](5))
print(names(ops))

Output:

[1] 6
[1] "inc" "neg"

A function can take several arguments and give some of them defaults, exactly like a named function:

area <- \(w, h = w) w * h
print(area(3))
print(area(3, 5))

Output:

[1] 9
[1] 15
challenge icon

Challenge

Easy

Complete the list ops with three anonymous functions of one argument:

  • double returns the argument times 2
  • square returns the argument times itself
  • negate returns the argument with its sign flipped

The supplied code reads the name of an operation and a number, calls that function from ops and prints the result.

Try it yourself

ops <- list(
  # Write your code here
  double = function(x) x
)

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
f <- ops[[input[1]]]
cat(f(as.numeric(input[2])), sep = "\n")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler