What Is Lapply In R?

This R code example introduces you to lapply in R and shows how to use it with a list as input.

Objective For ‘What is Lapply in R?’

This beginner-friendly R code will show you how to use lapply() in R, taking a list as input with the help of a simple example.

What Is Lapply In R?

The lapply() function in R is a powerful tool for applying a function to each element of a list or vector. It is a member of the apply() family of functions, which also includes sapply() and tapply().

The syntax for lapply() is as follows-

lapply(X, FUN, ...)

where, 

  • X is the input list or vector.

  • FUN is the function to be applied to each element of X.

  • ... are optional arguments that can be passed to FUN.

lapply() returns a list of the same length as X, with each element containing the result of applying FUN to the corresponding element of X.

The lapply() function also supports partial matching. This means that you can pass a pattern to the lapply() function and it will apply the function to each element of the list or vector that matches the pattern. You can avoid partial matching in lapply() using the exact = TRUE argument.

What Does lapply() Do In R?

lapply() is a very versatile function, and it can be used to perform a wide variety of tasks in R. For example, it can be used to-

  • Calculate summary statistics for each element of a list or vector.

  • Clean and pre-process data.

  • Perform feature engineering tasks.

  • Build and train machine learning models.

R lapply() Usage Examples

Here are some examples of how to use R lapply function-

  1. Calculate The Mean of Each Vector in a List

You can use lapply() to calculate the mean of each vector in a list using the following code-

my_list <- list(c(1, 2, 3), c(4, 5, 6), c(7, 8, 9))

means <- lapply(my_list, mean)

  1. Clean And Pre-Process a List of Strings

You can use lapply() to clean and preprocess a list of logical or character string using the following code-

my_strings <- list("Hello, world!", "This is a test.", "1234567890")

clean_strings <- lapply(my_strings, function(x) gsub("[[:punct:]]", "", x))

  1. Perform Feature Engineering On a Data Frame

You can use lapply() to perform feature engineering on a data frame using the following code-

my_df <- data.frame(x = c(1, 2, 3, 4), y = c(5, 6, 7, 8))

new_features <- lapply(my_df, function(x) x^2)

my_df <- cbind(my_df, new_features)

  1. Build A Machine-Learning Model

You can also use lapply() to build a machine-learning model using the following code-

my_model <- lm(y ~ x, data = my_df)

Check Out These End-To-End Solved R Projects To Accelerate Your Data Science Career

Steps Showing How To Use Lapply In R

The following steps will show you how to use the lapply() function in R by taking a list as input in an easy-to-understand example.

Step 1 - Import Libraries And Load Dataset

First, we create a list and a vector of multiples of 4.

vector_ = c(4,8,12,16,20,25)

Step 2 - Using lapply Function in R

In this step, we will use the lapply function with the following syntax-

lapply(X, FUN)

where-

X = list or vector,

FUN = function that needs to be applied to every element of a list or vector.

 # Squaring all the elements in a vector_ using a user-defined function

result = lapply(vector_, FUN =  function(i) i^2)

result

The output of the above code is-

  1. 16

  2. 64

  3. 144

  4. 256

  5. 400

  6. 625

What Are Some Other Functions Similar To lapply R?

Here are some other functions similar to the R function ‘lapply’-

1. apply() Function

Apply() functions in R allow you to apply a function to the rows or columns of a matrix or data frame. This function accepts a matrix or data frame as an input, along with the function and whether row- or column-wise application is required. It then returns the result as a vector value, array value, or list of values.

Syntax of apply() function-

apply( x, margin, function)

Where,

  • x- it is the input array, including a matrix.

  • margin- If the margin is 1, the function is applied across the row; if the margin is 2, it is applied across the column.

  • function- it is the function to be applied to input data.

2. sapply() Function

The sapply() function is a simplified form of lapply(). It takes in a vector, a list, or Data Frames as input, just as lapply() does, and tries to reduce the output object to the most simplified data structure. Thus, by default, the sapply() function outputs a vector for a vector, a list for a list of the same length, and a matrix for a Data Frame. It is the same as lapply(), with the only difference being the return object type.

Syntax of sapply() function-

sapply( X, FUN)

Where,

  • x- it is the input vector or an object.

  • fun- it is the function to be applied to input data.

Learn Real-World Uses Of Lapply in R With ProjectPro

This step-by-step R code example offers a clear understanding of what lapply() does in R and its several practical usage examples. We have learned how to leverage the power of this function to apply operations to list elements efficiently. Furthermore, if you want to expand your data science skillset and expertise, we recommend you explore the ProjectPro platform. By engaging with over 270 end-to-end solved projects in the ProjectPro repository, you can gain the skills and expertise needed to excel in data science and machine learning.

What Users are saying..

profile image

Gautam Vermani

Data Consultant at Confidential
linkedin profile url

Having worked in the field of Data Science, I wanted to explore how I can implement projects in other domains, So I thought of connecting with ProjectPro. A project that helped me absorb this topic... Read More

Relevant Projects

Forecasting Business KPI's with Tensorflow and Python
In this machine learning project, you will use the video clip of an IPL match played between CSK and RCB to forecast key performance indicators like the number of appearances of a brand logo, the frames, and the shortest and longest area percentage in the video.

Recommender System Machine Learning Project for Beginners-2
Recommender System Machine Learning Project for Beginners Part 2- Learn how to build a recommender system for market basket analysis using association rule mining.

Time Series Analysis with Facebook Prophet Python and Cesium
Time Series Analysis Project - Use the Facebook Prophet and Cesium Open Source Library for Time Series Forecasting in Python

Learn to Build a Polynomial Regression Model from Scratch
In this Machine Learning Regression project, you will learn to build a polynomial regression model to predict points scored by the sports team.

Predictive Analytics Project for Working Capital Optimization
In this Predictive Analytics Project, you will build a model to accurately forecast the timing of customer and supplier payments for optimizing working capital.

Learn to Build Generative Models Using PyTorch Autoencoders
In this deep learning project, you will learn how to build a Generative Model using Autoencoders in PyTorch

Walmart Sales Forecasting Data Science Project
Data Science Project in R-Predict the sales for each department using historical markdown data from the Walmart dataset containing data of 45 Walmart stores.

Create Your First Chatbot with RASA NLU Model and Python
Learn the basic aspects of chatbot development and open source conversational AI RASA to create a simple AI powered chatbot on your own.

Time Series Forecasting with LSTM Neural Network Python
Deep Learning Project- Learn to apply deep learning paradigm to forecast univariate time series data.

Expedia Hotel Recommendations Data Science Project
In this data science project, you will contextualize customer data and predict the likelihood a customer will stay at 100 different hotel groups.