How to Use lapply Function Instead of for-Loop in R (2 Examples)

This tutorial shows how to use the lapply function instead of for-loops in the R programming language.

Example 1: Applying for-Loop in R

for(index in 1:3) {                                # Head of for-loop
  print(paste("for-Loop Iteration No.", index))    # Creating output
}
# [1] "for-Loop Iteration No. 1"
# [1] "for-Loop Iteration No. 2"
# [1] "for-Loop Iteration No. 3"

Example 2: Faster Alternative: lapply Function Instead of for-Loop

invisible(lapply(1:3,                              # Avoid for-loop with lapply function
                 function(index) { print(paste("lapply() Function Iteration No.", index)) }
))
# [1] "lapply() Function Iteration No. 1"
# [1] "lapply() Function Iteration No. 2"
# [1] "lapply() Function Iteration No. 3"

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top