R Apply Functions
Apply Functions
In the For Loop chapter, you used a loop to do something with every item in a vector:
Example
numbers <- c(1, 2, 3, 4)
square <- function(x) {
x * x
}
for (x in numbers) {
print(square(x))
}
Try it Yourself »
R also has functions that do this for you, in one line. They are called apply functions. You give them a vector (or list) and a function, and they run the function on every item.
sapply()
The sapply() function runs a function on every item, and returns all the results in a vector:
Example
numbers <- c(1, 2, 3, 4)
square <- function(x) {
x * x
}
sapply(numbers, square)
Try it Yourself »
Note that you write square without parentheses. You give sapply() the function itself, and sapply() calls it for you.
This is useful for functions that work on one value at a time, like a function with an if statement:
Example
grade <- function(score) {
if (score > 50) {
"Pass"
} else {
"Fail"
}
}
sapply(c(85, 42, 78), grade)
Try it Yourself »
Anonymous Functions
If you only need a function once, you can write it directly inside sapply(), without giving it a name. This is called an anonymous function:
Example
numbers <- c(1, 2, 3, 4)
sapply(numbers, function(x) x * 10)
Try it Yourself »
Note: In R version 4.1 and newer, you can also write \(x) as a short form of function(x), for example sapply(numbers, \(x) x * 10).
lapply()
The lapply() function works like sapply(), but it always returns a list:
Example
fruits <- c("apple", "banana", "cherry")
lapply(fruits, toupper)
Try it Yourself »
You can also use apply functions on a list. Here, sapply() finds the average score of each player:
Example
scores <- list(Liam = c(80, 90), Jenny = c(70, 75, 95))
sapply(scores, mean)
Try it Yourself »
apply()
The apply() function runs a function on each row or each column of a matrix.
The second argument is 1 for rows and 2 for columns:
Example
thismatrix <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2)
thismatrix
apply(thismatrix, 1, sum)
apply(thismatrix, 2, sum)
Try it Yourself »
The sums of the rows are 9 and 12, and the sums of the columns are 3, 7 and 11.
Summary
| Function | Description |
|---|---|
| sapply() | Runs a function on every item, and returns a vector (if it can) |
| lapply() | Runs a function on every item, and returns a list |
| apply() | Runs a function on every row or column of a matrix |