What is sapply() in R programming with example?

apply functions in R are used to apply a function to a specific object, such as a vector or a matrix. The sapply() function is a wrapper around the lapply() function, which applies a function to each element of a list & returns a simplified result in a vector or matrix form.

Syntax

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

Parameters

The sapply() function in R takes two main parameters but optionally, simplify and USE.NAMES parameters can also be used.

  • X: The object to apply the function to. This can be a list, a vector, or an array.
  • FUN: The function to apply to each element of X.
  • simplify: A logical value that indicates whether to make simple the output into a vector or matrix. The default value is TRUE.
  • USE.NAMES: A logical value that indicates whether to use the names of the input object as the names of the output object. The default value is TRUE.

Return Values

The return value of sapply() depends on the simplify parameter. If simplify is TRUE, the output is a vector or matrix, depending on the input. If simplify is FALSE, the output is a list.

In general, the output of sapply() is the result of applying the function FUN to each element of the input X. If FUN returns a scalar value, sapply() returns a vector or matrix of these scalar values. If FUN returns a vector or list, sapply() returns a list or matrix of vectors or lists.

Coding Example: sapply() in R

# Create a list of student marks
marks <- list(John = c(70, 80, 75),
              Mary = c(65, 75, 80),
              Bob = c(80, 85, 90))

# Apply the mean function to each element of the list using sapply
sapply(marks, mean)
  1. Created a list called marks with three vectors, each containing the marks of a student in three different subjects.
  2. Using sapply() to apply the mean() function to each element of the list. sapply() takes two arguments: the list to apply the function to, and the function to apply. In this case, we apply the mean() function to each element of the marks list.
  3. The output of sapply() is a vector containing the mean mark of each student. The names of the vector will be the same as the names of the original list. We can see that John’s average mark is 75, Mary’s is 73.3, and Bob’s is 85.
  4. Note that sapply() returns a simplified result in a vector form. If we had used lapply() instead, the result would have been a list with one element for each student, each containing a single value of the mean mark.

Output

Stay in the Loop

Get the weekly email from Algoideas that makes reading the AI/ML stuff instructive. Join our mailing list to stay in the loop to stay informed, for free.

Latest stories

- Advertisement -

You might also like...