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:
# Using mtcars datasetdf <- data.frame(mtcars) # Factor levels on geardffactors <- factor(mtcars$gear) # Output maximum hp of each factor i.e., gearsby(df, dffactors, function(x){ m <- max(x$hp)}) |
Output:
dffactors: 3 [1] 245 ------------------------------------------------------------ dffactors: 4 [1] 123 ------------------------------------------------------------ dffactors: 5 [1] 335
Example 2:
# Using mtcars datasetdf <- data.frame(mtcars) # Factor levels on geardffactors <- factor(mtcars$gear) # Output mean of qsec of each factor i.e., gearsby(df, dffactors, function(x){ m <- mean(x$qsec)}) |
Output:
dffactors: 3 [1] 17.692 ------------------------------------------------------------ dffactors: 4 [1] 18.965 ------------------------------------------------------------ dffactors: 5 [1] 15.64

