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] 10R 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] 15Challenge
EasyComplete the list ops with three anonymous functions of one argument:
doublereturns the argument times 2squarereturns the argument times itselfnegatereturns 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")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler