在 R 编程中对不规则数组应用函数– tapply()函数
R 语言中的tapply()
函数用于将函数应用于由因子组合给出的向量子集
Syntax: tapply(vector, factor, fun)
Parameters:
vector: Created Vector
factor: Created Factor
fun: Function to be applied
示例 1:
# R Program to apply a function
# over a data object
# Creating Factor
fac <- c(1, 1, 1, 1, 2, 2, 2, 3, 3)
# Created Vector
vec <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)
# Calling tapply() Function
tapply(vec, fac, sum)
输出:
1 2 3
10 18 17
上面的代码是这样工作的:
示例 2:
# R Program to apply a function
# over a data object
# Creating Factor
fac <- c(1, 1, 1, 1, 2, 2, 2, 3, 3)
# Created Vector
vec <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)
# Calling tapply() Function
tapply(vec, fac, prod)
输出:
1 2 3
24 210 72