The lapply() function in R can be used to apply a function to each element of a list, vector, or data frame and obtain a list as a result.
The sapply() function can also be used to apply a function to each element of a list, vector, or data frame but it returns a vector as a result.
The following examples show how to use each of these functions in R.
Example: How to Use lapply() in R
The following code shows how to use the lapply() function to multiply each value in each column of a data frame by 2:
#create data frame df frame(x=c(1, 2, 2, 3, 5), y=c(4, 4, 6, 7, 8), z=c(7, 7, 9, 9, 9)) #view data frame df x y z 1 1 4 7 2 2 4 7 3 2 6 9 4 3 7 9 5 5 8 9 #multiply each value in each column by 2 lapply(df, function(df) df*2) $x [1] 2 4 4 6 10 $y [1] 8 8 12 14 16 $z [1] 14 14 18 18 18
Notice that the result is a list.
Example: How to Use sapply() in R
The following code shows how to use the sapply() function to multiply each value in each column of a data frame by 2:
#create data frame df frame(x=c(1, 2, 2, 3, 5), y=c(4, 4, 6, 7, 8), z=c(7, 7, 9, 9, 9)) #view data frame df x y z 1 1 4 7 2 2 4 7 3 2 6 9 4 3 7 9 5 5 8 9 #multiply each value in each column by 2 sapply(df, function(df) df*2) x y z [1,] 2 8 14 [2,] 4 8 14 [3,] 4 12 18 [4,] 6 14 18 [5,] 10 16 18
Notice that the result is a matrix of vectors.
Note that you can use as.data.frame() to return a data frame as a result instead of a matrix:
#multiply each value in each column by 2 and return a data frame as.data.frame(sapply(df, function(df) df*2)) x y z 1 2 8 14 2 4 8 14 3 4 12 18 4 6 14 18 5 10 16 18
When to Use lapply() vs. sapply()
In 99% of cases, you’ll use sapply() because it makes the most sense to return a vector or matrix as a result.
However, in some rare circumstances you may need to use lapply() instead if you need the result to be a list.
Note that sapply() and lappy() perform the same operations on a vector, matrix, or data frame. The only difference is the class of the object that is returned.
Additional Resources
How to Apply Function to Each Row of Data Frame in R
How to Use colSums() Function in R
How to Use rowSums() Function in R