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 datasetINDICES:represents the factor list of datasetFUN:represents the function to be performed on factor levels

**Example 1:**

`# 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)` `})` |

**Output:**

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

**Example 2:**

`# 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)` `})` |

**Output:**

dffactors: 3 [1] 17.692 ------------------------------------------------------------ dffactors: 4 [1] 18.965 ------------------------------------------------------------ dffactors: 5 [1] 15.64

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready.