### sapply in R

The sapply() function behaves similarly to lapply(); the only real difference is in the return value. sapply() will try to simplify the result of lapply() if possible. Essentially, sapply() calls lapply()

on its input and then applies the following steps:

1. If the result is a list where every element is length 1, then a vector is returned
2. If the result is a list where every element is a vector of the same length (> 1), a matrix is returned.
3. If it can’t figure things out, a list is returned

To get the help file type the following code.

?sapply()

The body of the sapply() function can be seen here by just typing sapply in your console. sapply

Output:

function (X, FUN, …, simplify = TRUE, USE.NAMES = TRUE)
{
FUN <- match.fun(FUN)
answer <- lapply(X = X, FUN = FUN, …)
if (USE.NAMES && is.character(X) && is.null(names(answer)))
if (!identical(simplify, FALSE) && length(answer))
simplify2array(answer, higher = (simplify == “array”))
}
<bytecode: 0x000000000f994120>
<environment: namespace:base>

#### Example: x <- list(a = 1:10, b = rep(10,10), c = rnorm(10))
x
lapply(x, sum)
sapply(x, sum)

Output:

> x
\$a
 1 2 3 4 5 6 7 8 9 10

\$b
 10 10 10 10 10 10 10 10 10 10

\$c
 -1.0039491 -0.6831659 0.6343053 0.7298642 -0.4142943 -0.7717037 1.0150913 -0.1714354 0.3530912 0.4718342

> lapply(x, sum)
\$a
 55

\$b
 100

\$c
 0.1596377

sapply(x, sum)
a b c
55.0000000 100.0000000 0.1596377

Check the difference in the output for lapply and sapply. Because the result of lapply() was a list where each element had length 1, sapply() collapsed the output into a numeric vector, which is often more useful than a list.

#### Example 2: x <- 1:5
sapply(x, runif, min = 0, max = 5)

Output:

[]
 3.772212

[]
 1.5118754 0.7759651

[]
 0.9903887 4.9451553 3.2073191

[]
 1.6318879 2.9374652 0.7642016 4.7481609

[]
 2.6468426 3.7913182 3.7799668 4.5520162 0.9024251

Here the output is a list. For this case lapply and sapply result is same.