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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate
# sapply function
  
# Getting the value of Biochemical oxygen
# demand data set
BOD
  
# Calling sapply() function which
# will sum the data of each columns
# of BOD
sapply(BOD, sum)

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate
# sapply function
  
# Initializing a list
mylist <- 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 elements
sapply(mylist, mean)

chevron_right


Output:

[1] 2.5 5.0 4.0
My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.