0
0
R Programmingprogramming~5 mins

lapply and sapply in R Programming

Choose your learning style9 modes available
Introduction

Use lapply and sapply to run a function on each item in a list or vector easily. They help you avoid writing loops.

You want to apply the same calculation to every item in a list.
You have a vector and want to transform each element quickly.
You want to get results back as a list or a simpler vector/matrix.
You want cleaner, shorter code instead of writing loops.
You want to process data step-by-step in a functional style.
Syntax
R Programming
lapply(X, FUN, ...)
sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)

X is the list or vector you want to process.

FUN is the function you want to apply to each element.

Examples
Multiply each number in the list by 2, result is a list.
R Programming
lapply(list(1, 2, 3), function(x) x * 2)
Calculate square root of each number, result is a vector.
R Programming
sapply(c(1, 2, 3), sqrt)
Sum each vector inside the list, result is a list with sums.
R Programming
lapply(list(a = 1:3, b = 4:6), sum)
Sum each vector inside the list, result is a named vector with sums.
R Programming
sapply(list(a = 1:3, b = 4:6), sum)
Sample Program

This program doubles each number in a list using both lapply and sapply. It shows the difference in output types.

R Programming
numbers <- list(2, 4, 6)
double_list <- lapply(numbers, function(x) x * 2)
double_vector <- sapply(numbers, function(x) x * 2)

print(double_list)
print(double_vector)
OutputSuccess
Important Notes

lapply always returns a list, even if the result is simple.

sapply tries to simplify the result to a vector or matrix if possible.

If sapply cannot simplify, it returns a list like lapply.

Summary

lapply and sapply help apply functions to each item in a list or vector.

lapply returns a list, sapply returns a simpler structure if possible.

They make your code shorter and easier to read than loops.