Jaehee Hur
Jaehee Hur

Reputation: 23

Why do sapply() and lapply() have same result?

I am new to R. I was practicing lapply() and sapply() function: lapply() returns list, and sapply() returns as vector/matrix. Now there I don't understand why do lapply() and sapply() have same result as a list?

> x1 <- lapply(list(1:3, 25:29), function(x) {2*x})
> x2 <- sapply(list(1:3, 25:29), function(x) {2*x})
> x1
[[1]]
[1] 2 4 6

[[2]]
[1] 50 52 54 56 58

> x2
[[1]]
[1] 2 4 6

[[2]]
[1] 50 52 54 56 58

> str(x2)
List of 2
 $ : num [1:3] 2 4 6
 $ : num [1:5] 50 52 54 56 58
> mode(x2)
[1] "list"

After, I checked unlist() and it return same input as a vector. It's hard to understand why do sapply() return list type as a result.

Thank you.

Upvotes: 2

Views: 199

Answers (1)

akrun
akrun

Reputation: 887901

If the length of the list elements are not the same, sapply will not coerce it to matrix and will have the same result as lapply

We can check the Usage of ?sapply and ?lapply

lapply(X, FUN, ...)

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

The simplify=TRUE is the one that converts a list of equal length output to a matrix

Upvotes: 5

Related Questions