sapply in R: How to Use R sapply() Function

The sapply() function in R works like lapply(), but it tries to interpret the output to the most fundamental data structure possible, either Vector or Matrix. The sapply() is a wrapper” function for lapply().

The apply() function returns the vector or array by applying a function to the margins of the array or matrix. The lapply() function is useful for performing operations on list objects and returns the list object of the same length as the original set.

R sapply()

The sapply() is a built-in R wrapper class to lapply, with the difference being it returns a vector or matrix instead of a list object. The sapply() function applies a function to all the elements of the input. Thus, it takes a list, vector, or data frame as an argument and returns a vector or matrix.

Syntax

sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)

Parameters

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 a name for the result unless it had names already.

Implementation of  sapply() function

rv <- 1:10
rv2 <- 11:20

l <- list(a = rv, b = rv2) 
sapply(l, mean)

Output

  a    b
 5.5  15.5

Now, let’s use the lapply() function instead of sapply() function.

rv <- 1:10
rv2 <- 11:20

l <- list(a = rv, b = rv2)
lapply(l, mean)

Output

$a
[1] 5.5

$b
[1] 15.5

The sapply() function is more efficient than lapply() because sapply() stores values directly into a vector. If you apply the lapply() function, then it would give us a list unless you pass simplify=FALSE as a parameter to sapply(). Then, a list will be returned.

Using sapply() function to 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 how to use the sapply() function on R Vector.

rv <- 19:21
sapply(rv, function(f) f ^ 2)

Output

[1] 361 400 441

Using sapply and lapply in R

The sapply() function returns the output in Vector or Matrix.

The lapply() function returns the output in List.

We can use the lapply() or sapply() function interchangeably to slice the data frame. 

That is it for the sapply() function in R.

2 thoughts on “sapply in R: How to Use R sapply() Function”

  1. Stumbled into this website by chance but I’m sure glad I clicked on that link. You positively answered all the questions I have been dying to answer for some time now. Will definitely come back for more of this. Thank you so much

    Reply

Leave a Comment