R Language: sapply()

0

The sapply() function is a variation of the lapply() function that attempts to simplify the output of lapply() to a vector, matrix, or array. This can be useful if you are applying a function to a list of vectors and you want to avoid the overhead of creating a list of lists.

The sapply() function works by first calling lapply() on its input. If the result of lapply() is a list where every element is length 1, then sapply() returns a vector. If the result of lapply() is a list where every element is a vector of the same length (> 1), then sapply() returns a matrix. If the result of lapply() is a list where the elements are not all the same length, then sapply() returns a list.

Here is an example of how sapply() works.

x <- list(a = 1:4, b = rnorm(10), c = rnorm(20, 1), d = rnorm(100, 5))


# lapply() returns a list

lapply(x, mean)

$a

[1] 2.5


$b

[1] -0.251483


$c

[1] 1.481246


$d

[1] 4.968715


# sapply() collapses the output into a vector

sapply(x, mean)

[1] 2.500000 -0.251483  1.481246  4.968715

As you can see, the output of sapply() is a vector, even though the output of lapply() is a list. This is because the elements of the output of lapply() are all length 1.

The sapply() function can be a useful tool for simplifying the output of lapply(). However, it is important to note that sapply() may not always be able to simplify the output. If the output of lapply() is a list where the elements are not all the same length, then sapply() will return a list.

Post a Comment

0Comments
Post a Comment (0)