在 R 编程中将用户定义的函数应用于数据集的因子水平 – by()函数
R 编程中的by()
函数是一个面向对象的包装函数,它在函数调用的参数中传递的数据集的因子级别上执行提供的函数。
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
示例 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)
})
输出:
dffactors: 3
[1] 245
------------------------------------------------------------
dffactors: 4
[1] 123
------------------------------------------------------------
dffactors: 5
[1] 335
示例 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)
})
输出:
dffactors: 3
[1] 17.692
------------------------------------------------------------
dffactors: 4
[1] 18.965
------------------------------------------------------------
dffactors: 5
[1] 15.64