Applying User-defined Functions on Factor Levels of Dataset in R Programming – by() Function
Last Updated :
01 Jun, 2020
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:
df < - data.frame(mtcars)
dffactors < - factor(mtcars$gear)
by(df, dffactors, function(x){
m < - max (x$hp)
})
|
Output:
dffactors: 3
[1] 245
------------------------------------------------------------
dffactors: 4
[1] 123
------------------------------------------------------------
dffactors: 5
[1] 335
Example 2:
df < - data.frame(mtcars)
dffactors < - factor(mtcars$gear)
by(df, dffactors, function(x){
m < - mean(x$qsec)
})
|
Output:
dffactors: 3
[1] 17.692
------------------------------------------------------------
dffactors: 4
[1] 18.965
------------------------------------------------------------
dffactors: 5
[1] 15.64
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...