在 R 编程中对对象应用函数– sapply()函数
R 语言中的sapply()
函数将列表、向量或数据框作为输入,并以向量或矩阵的形式给出输出。它对于对列表对象的操作很有用,并返回与原始集合长度相同的列表对象。
Syntax: sapply(X, FUN)
Parameters:
X: A vector or an object
FUN: Function applied to each element of x
示例 1:
# R program to illustrate
# sapply function
# Getting the value of Biochemical oxygen
# demand data set
BOD
# Calling sapply() function which
# will sum the data of each columns
# of BOD
sapply(BOD, sum)
输出:
Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8
Time demand
22 89
示例 2:
# R program to illustrate
# sapply function
# Initializing a list
mylist <- list(c(1, 2, 3, 4), c(2, 4, 6, 8), c(1, 3, 5, 7))
# Calling the sapply() function which
# will calculate mean of each vector elements
sapply(mylist, mean)
输出:
[1] 2.5 5.0 4.0