lapply()

Using “for” loop in R for iterating over a list or vector takes a lot of memory and it is quite slow also. And when it comes to dealing with large data set and iterating over them, for loop is not advised. R provides many alternatives to be applied to lists for looping operations that are pretty useful when working interactively on a command line. lapply() function is one of those functions and it is used to apply a function over a list.

Syntax: lapply(List, Operation)

Arguments:

  • List: list containing a number of objects
  • Operation: length, sum, mean, and cumsum

Return value: Returns a numeric value

lapply() function is used with a list and performs the following operations:

  • lapply(List, length): Returns the length of objects present in the list, List.
  • lapply(List, sum): Returns the sum of elements held by objects in the list, List.
  • lapply(List, mean): Returns the mean of elements held by objects in the list, List.
  • lapply(List, cumsum): Returns the cumulative sum of elements held by objects present inside the list, List.

Difference Between lapply() VS sapply() in R

A list in R Programming Language can be passed as an argument in lapply() and sapply() functions. It is quite helpful to perform some of the general operations like calculation of sum, cumulative sum, mean, etc of the elements in the objects held by a list.   

Similar Reads

lapply()

Using “for” loop in R for iterating over a list or vector takes a lot of memory and it is quite slow also. And when it comes to dealing with large data set and iterating over them, for loop is not advised. R provides many alternatives to be applied to lists for looping operations that are pretty useful when working interactively on a command line. lapply() function is one of those functions and it is used to apply a function over a list....

sapply()

This function is also used to apply a function over a list but with simplified results....

Difference between  lapply() and sapply() functions:

lapply() function displays the output as a list whereas sapply() function displays the output as a vector. lapply() and sapply() functions are used to perform some operations in a list of objects. sapply() function in R is more efficient than lapply() in the output returned because sapply() stores values directly into a vector....

Returning output as a list using sapply() function

...