The sapply() function in R is “used to apply a function to all the input elements of a list or vector and returns a vector or matrix of the results”.
sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)
- X: It is a vector or List appropriate to a call to sapply.
- FUN: It is a function.
- …: It is the optional argument to FUN.
- simplify: It is a logical value that should the result be simplified to a vector or matrix if possible.
- USE.NAMES: It is a logical value; if TRUE and X are characters, use X as the result’s name unless it already has names.
Example 1: R program to use the sapply() function
To use the sapply() function in R, you must define the List or Vector you want to iterate on the first parameter and the function you wish to apply to each vector element in the second argument.
Let’s take the above example, where we used for loop to calculate the cube of each vector element.
sapply(1:5, function(num) num ^ 3)
 1 8 27 64 125
You can see that we got a cube of all the vector elements just with one line of code.
Example 2: Using sapply() function with a list
rv <- 1:10 rv2 <- 11:20 l <- list(a = rv, b = rv2) sapply(l, mean)
a b 5.5 15.5
Let’s use the lapply() function instead of the sapply() function.
rv <- 1:10 rv2 <- 11:20 l <- list(a = rv, b = rv2) lapply(l, mean)
$a  5.5 $b  15.5
The sapply() function is more efficient than lapply() because sapply() stores values directly into a vector.
Applying the lapply() function would give us a list unless you pass simplify=FALSE as a parameter to sapply(). Then, a list will be returned.
Example 3: Using the sapply() function with R Vector
You can apply the sapply() function to a Vector. It returns the processed output. For example, if we want the square of all vector elements, we use the sapply() function and pass the two arguments.
- A vector: It is the vector that contains elements
- A function: The logic of square means the function that returns the square of the elements.
See the following code on using the sapply() function on R Vector.
rv <- 19:21 sapply(rv, function(f) f ^ 2)
 361 400 441
Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.
1 thought on “How to Use the sapply() Function in R”
I really like what you posted. I really agree with what you wrote.