Applying a Function over an Object in R Programming – sapply() Function
sapply() function in R Language takes list, vector or data frame as input and gives output in vector or matrix. It is useful for operations on list objects and returns a list object of same length of original set.
Syntax: sapply(X, FUN)
Parameters:
X: A vector or an object
FUN: Function applied to each element of x
Example 1:
# R program to illustrate# sapply function # Getting the value of Biochemical oxygen# demand data setBOD # Calling sapply() function which# will sum the data of each columns# of BODsapply(BOD, sum) |
Output:
Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8
Time demand
22 89
Example 2:
# R program to illustrate# sapply function # Initializing a listmylist <- list(c(1, 2, 3, 4), c(2, 4, 6, 8), c(1, 3, 5, 7)) # Calling the sapply() function which# will calculate mean of each vector elementssapply(mylist, mean) |
Output:
[1] 2.5 5.0 4.0


.png)
