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

Ray han

Tech Leader | Stanford / Yale University
linkedin profile url

I think that they are fantastic. I attended Yale and Stanford and have worked at Honeywell,Oracle, and Arthur Andersen(Accenture) in the US. I have taken Big Data and Hadoop,NoSQL, Spark, Hadoop... Read More

Relevant Projects

MLOps Project on GCP using Kubeflow for Model Deployment
MLOps using Kubeflow on GCP - Build and deploy a deep learning model on Google Cloud Platform using Kubeflow pipelines in Python

Loan Default Prediction Project using Explainable AI ML Models
Loan Default Prediction Project that employs sophisticated machine learning models, such as XGBoost and Random Forest and delves deep into the realm of Explainable AI, ensuring every prediction is transparent and understandable.

Ola Bike Rides Request Demand Forecast
Given big data at taxi service (ride-hailing) i.e. OLA, you will learn multi-step time series forecasting and clustering with Mini-Batch K-means Algorithm on geospatial data to predict future ride requests for a particular region at a given time.

BigMart Sales Prediction ML Project in Python
The goal of the BigMart Sales Prediction ML project is to build and evaluate different predictive models and determine the sales of each product at a store.

Build a Logistic Regression Model in Python from Scratch
Regression project to implement logistic regression in python from scratch on streaming app data.

Build a Customer Churn Prediction Model using Decision Trees
Develop a customer churn prediction model using decision tree machine learning algorithms and data science on streaming service data.

Deploy Transformer-BART Model on Paperspace Cloud
In this MLOps Project you will learn how to deploy a Tranaformer BART Model for Abstractive Text Summarization on Paperspace Private Cloud

MLOps using Azure Devops to Deploy a Classification Model
In this MLOps Azure project, you will learn how to deploy a classification machine learning model to predict the customer's license status on Azure through scalable CI/CD ML pipelines.

BERT Text Classification using DistilBERT and ALBERT Models
This Project Explains how to perform Text Classification using ALBERT and DistilBERT

Azure Text Analytics for Medical Search Engine Deployment
Microsoft Azure Project - Use Azure text analytics cognitive service to deploy a machine learning model into Azure Databricks