We use the apply family to run the same task on many items quickly and simply. Loops do this too, but apply functions are often shorter and easier to read.
0
0
Apply family vs loops in R Programming
Introduction
When you want to do the same calculation on each row or column of a table.
When you want to repeat a function on every item in a list without writing a loop.
When you want cleaner and faster code than writing for or while loops.
When you want to avoid mistakes that can happen in loops by using built-in functions.
When you want to write code that is easier to understand and maintain.
Syntax
R Programming
apply(X, MARGIN, FUN, ...) lapply(X, FUN, ...) sapply(X, FUN, ...) tapply(X, INDEX, FUN = NULL, ...) mapply(FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE, USE.NAMES = TRUE)
apply() works on matrices or arrays; MARGIN = 1 for rows, 2 for columns.
lapply() returns a list; sapply() tries to simplify the result.
Examples
Sum each row of a 2x3 matrix using
apply().R Programming
apply(matrix(1:6, nrow=2), 1, sum)
Square each number in a list using
lapply().R Programming
lapply(list(1, 2, 3), function(x) x^2)
Same as above but returns a vector instead of a list.
R Programming
sapply(list(1, 2, 3), function(x) x^2)
Using a loop to print squares of numbers 1 to 3.
R Programming
for(i in 1:3) { print(i^2) }
Sample Program
This program shows three ways to square numbers in a list: with lapply(), sapply(), and a for loop. It prints the results so you can see they are the same.
R Programming
numbers <- list(1, 2, 3, 4, 5) # Using lapply to square each number squares_lapply <- lapply(numbers, function(x) x^2) print("Squares with lapply:") print(squares_lapply) # Using sapply to square each number squares_sapply <- sapply(numbers, function(x) x^2) print("Squares with sapply:") print(squares_sapply) # Using a for loop to square each number squares_loop <- vector("numeric", length(numbers)) for(i in seq_along(numbers)) { squares_loop[i] <- numbers[[i]]^2 } print("Squares with for loop:") print(squares_loop)
OutputSuccess
Important Notes
Apply functions often run faster than loops in R.
Use lapply() when you want a list back, sapply() when you want a simpler result like a vector.
Loops are more flexible but can be longer and harder to read.
Summary
Apply family functions help repeat tasks on many items easily.
They often make code shorter and clearer than loops.
Choose the right apply function based on the input and desired output.