What is the difference between lapply vs sapply


  R Interview Questions

For a more comprehensive list of R Interview questions, visit the link.

sapply () is just a wrapper around lapply (). lapply returns a list whereas sapply returns a vector.

# Here is a small data frame of iris data set. 
> iris_small
    Sepal.Length Sepal.Width Petal.Length Petal.Width
1            5.1         3.5          1.4         0.2
2            4.9         3.0          1.4         0.2
3            4.7         3.2          1.3         0.2
51           7.0         3.2          4.7         1.4
52           6.4         3.2          4.5         1.5
53           6.9         3.1          4.9         1.5
101          6.3         3.3          6.0         2.5
102          5.8         2.7          5.1         1.9
103          7.1         3.0          5.9         2.1

Let’s convert this into a List ( which you don’t need to to perform lapply function, but just play along for now )

> iris_small_list = as.list(iris_small)
$Sepal.Length
[1] 5.1 4.9 4.7 7.0 6.4 6.9 6.3 5.8 7.1
$Sepal.Width
[1] 3.5 3.0 3.2 3.2 3.2 3.1 3.3 2.7 3.0
$Petal.Length
[1] 1.4 1.4 1.3 4.7 4.5 4.9 6.0 5.1 5.9
$Petal.Width
[1] 0.2 0.2 0.2 1.4 1.5 1.5 2.5 1.9 2.1

Let’s calculate the mean across each of the list elements

> means = lapply(iris_small_list,mean)
> means
$Sepal.Length
[1] 6.022222
$Sepal.Width
[1] 3.133333
$Petal.Length
[1] 3.911111
$Petal.Width
[1] 1.277778

Each element of the list element gets sent to the mean function as an argument and the result is returned in a list finally.

Now, let’s perform the same with sapply

> means = sapply(iris_small_list,mean)
> means
Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
    6.022222     3.133333     3.911111     1.277778

This time the list elements are converted to a vector.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.