Problem: Iteration through a long list or vector using a for loop takes tremendous amount of time.
This problem is solved by using apply family of functions in R. This family of functions can be fed with many built-in functions to perform different tasks on the collection of objects such as list, vector, dataframe etc.
The family of apply functions are listed below:
lapply() is a function that takes a vector,list or data frame as input and gives the output as list by appplying a certain operation on it.
This recipe demonstrates how to use the lapply() using a list as input
We create a list and a vector of multiples of 4
vector_ = c(4,8,12,16,20,25)
Using the lapply() wuth the following syntax:
# squaring the elements in a vector_ using a user defined function result = lapply(vector_, FUN = function(i) i^2) result
64 144 256 400 625
NOTE: You can see the that the output of both is a list