Apply a function over a vector or list
Featured in 3 main posts
R offers the option to repeat a function over elements of a vector or list and return the results in a new list.
Example
Consider the following task:
Get the five sequences of integers that end on 10 and start on 3, 6, 2, 7 and 5.
We can split this task into the variable parameter and the action.
-
Variable parameter: starting point
Let’s represent our 5 different starting points with a vector:
c(3,6,2,7,5)
-
Action: get sequences of integers that start from any given starting point and end on 10
We need a function that performs this for any of our starting points:
function(start.point) {
return(start.point:10)
}
To understand the syntax of this function, see more details on creating number sequences.
We now need to combine them: apply the action on each instance of the variable parameter.
The lapply function is the glue that binds these together: it iterates the function, applying it to individual elements of a vector (or list) and returns the results as a list of the same length.
The following piece of code returns the result as a list of sequence vectors:
lapply(
X=c(3,6,2,7,5),
FUN=function(start.point) {
return(start.point:10)
}
)
## [[1]]
## [1] 3 4 5 6 7 8 9 10
##
## [[2]]
## [1] 6 7 8 9 10
##
## [[3]]
## [1] 2 3 4 5 6 7 8 9 10
##
## [[4]]
## [1] 7 8 9 10
##
## [[5]]
## [1] 5 6 7 8 9 10
Arguments:
-
X(uppercase): The vector or list representing the variable parameter. -
FUN: The function carrying out the action. -
start.point: Argument taking the value of eachXelement within the applied function.
We can also pass the end point inside the function as an argument whose value does not change between iterations. To do this, write it after the function’s closing curly bracket, separated by a comma, and write its name as an argument of the function.
In this case, we name it end.point and give it the value 10.
lapply(
X=c(3,6,2,7,5),
FUN=function(start.point,end.point) {
return(start.point:end.point)
},end.point=10
)
## [[1]]
## [1] 3 4 5 6 7 8 9 10
##
## [[2]]
## [1] 6 7 8 9 10
##
## [[3]]
## [1] 2 3 4 5 6 7 8 9 10
##
## [[4]]
## [1] 7 8 9 10
##
## [[5]]
## [1] 5 6 7 8 9 10
See the documentation file on lapply for more details.