Explain with an example how to perform lapply() function using R.
To apply lapply() to a function, we have to define a vector
# vector
v <- c(1,2,3,4,5)
Here v is a vector consisting of numbers ranging from 1 to 5.Now let us build a custom function to see how lapply() works.
# our custom function
addrand <- function(x){
# Get a random number
ran <-sample(x=1:10,1)
# return x plus the random number
return(x+ran)
}
# lapply()
lapply(v,addrand)
This will give the following output
- 7
- 11
- 9
- 5
- 6