What is lapply() in R programming with example?

In R programming, lapply() is a function that stands for “list apply”. It is used to apply a function to each element of a list or a vector and then returns a list of the results.


lapply(X, FUN, ...)


This function lapply() takes the following argument values:

  • X: is a list or a vector.
  • FUN: is the function to apply to each element of X.
  • : are optional arguments to be passed to FUN.

Return Values

The returned value of lapply() is a list containing the results of applying FUN to each element of X. The length of the output list is the same as the length of X.

Code Example of lapply() function in r

Let’s discuss a real-word scenario where we have a list of files in a directory, and you want to get the file size of each file in megabytes (MB). You can use the lapply() function to apply the file.size() function to each file in the list, and then convert the result from bytes to MB.

# List all files in directory
files <- list.files(path = "/path/to/directory/")

# Define function to get file size in MB
get_file_size_MB <- function(file) {
  size_in_bytes <- file.size(file)
  size_in_MB <- size_in_bytes / 1024^2

# Apply get_file_size_MB to each file using lapply
file_sizes <- lapply(files, get_file_size_MB)

# Print the result
  • Line#2: Lists all the files in a directory specified by the path argument, and stores the list of file names in the files variable. The list.files() function is a built-in function in R that returns a character vector of the file names in the specified directory.
  • Line#4-9: This code defines a new function get_file_size_MB() that takes a file name as input, gets the file size in bytes using the file.size() function, and converts the result to MB by dividing by 10242. The function then returns the size in MB.
  • Line#12: Applies the get_file_size_MB() function to each file in the files list using the lapply() function. The lapply() function takes two arguments: a list or vector (files in this case), and a function (get_file_size_MB in this case) to apply to each element of the list. The result of lapply() is a list of the function output applied to each element of the input list. In this case, file_sizes is a list containing the file sizes in MB.
  • Line#15: Print the file_sizes list to the console. This is just a convenient way to see the output of the lapply() function.

Stay in the Loop

Get the weekly email from Algoideas that makes reading the AI/ML stuff instructive. Join our mailing list to stay in the loop to stay informed, for free.

Latest stories

- Advertisement -

You might also like...