How to Use the sapply() Function in R

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)


  1. X: It is a vector or List appropriate to a call to sapply.
  2. FUN: It is a function.
  3. …: It is the optional argument to FUN.
  4. simplify: It is a logical value that should the result be simplified to a vector or matrix if possible.
  5. 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] 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)


[1] 5.5

[1] 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.

  1. A vector: It is the vector that contains elements
  2. 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)


[1] 361 400 441

That’s it.

1 thought on “How to Use the sapply() Function in R”

Leave a Comment