Applying User-defined Functions on Factor Levels of Dataset in R Programming – by() Function

by() function in R programming is an object-oriented wrapper function which performs the provided function on factor levels of the data set passed in the arguments of function call.

Syntax: by(data, INDICES, FUN)

Parameters:

data: represents the dataset
INDICES: represents the factor list of dataset
FUN: represents the function to be performed on factor levels

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

# Using mtcars dataset
df <- data.frame(mtcars)
  
# Factor levels on gear
dffactors <- factor(mtcars$gear)
  
# Output maximum hp of each factor i.e., gears
by(df, dffactors, function(x){
  m <- max(x$hp)
})

chevron_right


Output:

dffactors: 3
[1] 245
------------------------------------------------------------ 
dffactors: 4
[1] 123
------------------------------------------------------------ 
dffactors: 5
[1] 335

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Using mtcars dataset
df <- data.frame(mtcars)
  
# Factor levels on gear
dffactors <- factor(mtcars$gear)
  
# Output mean of qsec of each factor i.e., gears
by(df, dffactors, function(x){
  m <- mean(x$qsec)
})

chevron_right


Output:

dffactors: 3
[1] 17.692
------------------------------------------------------------ 
dffactors: 4
[1] 18.965
------------------------------------------------------------ 
dffactors: 5
[1] 15.64
My Personal Notes arrow_drop_up

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.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.