用R语言在写函数的时候,会经常用到apply函数,从而避免在R中使用循环,R语言中的apply函数主要有apply()、tapply()、lapply()、tapply()。各种apply函数很容易搞混淆,因此在这里记录一下。
1. apply()函数
apply(X,MARGIN,FUN),输入为dataframe或matrix,以矢量、列表、数组形式输出,参数解释:
- X:dataframe或matrix
- MARGIN:dataframe/matrix的行或列,
- MARGIN=1:对行进行操作
- MARGIN=2:对列执行操作
- FUN:对数据框、矩阵执行的操作
例如:
1 | > m1 <- matrix((1:10),nrow=4, ncol=5,byrow=F) |
2. lapply()函数
lapply(X,FUN),输入为list、vector或data.frame,并返回与原始集合长度相同的列表list,lapply不需要MARGIN。
- X:向量vector或者object
- FUN:对X的每个元素执行的操作
1 | > m2 <- c("A","B","C","D") |
我们可以使用unlist()将列表转换为向量。
1 | > m2_lower2 <- unlist(lapply(m2,tolower)) |
3.sapply()函数
sapply()函数将列表、向量、数据框等作为输入,以向量或矩阵的形式输出。
sapply(X,FUN)
- X:vector or object
- FUN:执行的操作函数
1 | > m3 <- cars |
sapply()函数执行的功能与lapply()函数相同,sapply()函数返回一个向量,lapply()函数返回一个向量。
apply()、sapply()、lapply()之间的区别:
Function | Arguments | Objective | Input | Output |
---|---|---|---|---|
apply | apply(x, MARGIN, FUN) | Apply a function to the rows or columns or both | Data.frame or matrix | vector, list, array |
lapply | lapply(X, FUN) | Apply a function to all the elements of the input | List, vector or data.frame | list |
sapply | sappy(X FUN) | Apply a function to all the elements of the input | List, vector or data.frame | vector or matrix |
4.tapply()函数
tapply()计算向量中每个因子变量的度量(均值、中位数、最小值、最大值等)或函数,即对数据分组进行运算。也可以创建向量的子集,然后将FUN函数应用于每个子集。
tapply(X,INDEX,FUN=NULL,simplify=TRUE)
- X:object,通常是vector
- INDEX:一个list对象,且该list中的每一个元素都是与X有同样长度的因子
- FUN:是需要计算的函数
- simplify是逻辑变量,若取值为TRUE(默认值),且函数FUN的计算结果总是为一个标量值,那么函数tapply返回一个数组;若取值为FALSE,则函数tapply的返回值为一个list对象。
1 | > iris |
tapply()函数的INDEX也可以是多列的组合,例如:
1 | > newiris$Sepal.Length_compare_with_5<-ifelse(newiris$Sepal.Length>5.0,"over_than_5","lower_than_5") |
参考资料:
1.https://zhuanlan.zhihu.com/p/26029242 这个里面有更多关于apply函数的详细解释,非常有帮助!