apply(), lapply(), sapply(), tapply()的区别

1.apply()函数

apply的输入为data.frame或matrix,输出为 vector, list or array。

apply(X, MARGIN, FUN)
Here:
-x: an array or matrix
-MARGIN: take a value or range between 1 and 2 to define where to apply the function:
-MARGIN=1: the manipulation is performed on rows -MARGIN=2: the manipulation is performed on columns
-MARGIN=c(1,2)` the manipulation is performed on rows and columns
-FUN: tells which function to apply. Built functions like mean, median, sum, min, max and even user-defined functions can be applied

2.lapply() function

lapply()函数输入为 list, vector or data.frame,输出为list。

lapply(X, FUN)
Arguments:
-X: A vector or an object
-FUN: Function applied to each element of x


3.sapply() function

sapply() 输入为 list, vector or data.frame ,输出为 vector or matrix. sapply()与 lapply() 可以完成相同的工作,但是输出的格式不一样。

sapply(X, FUN)
Arguments:
-X: A vector or an object
-FUN: Function applied to each element of x

image.png

一张总结的图:


4.tapply() function

tapply() 用于对一个vector做一个函数运算 (如:mean, median, min, max, etc..) 。

tapply(X, INDEX, FUN = NULL)
Arguments:
-X: An object, usually a vector
-INDEX: A list containing factor
-FUN: Function applied to each element of x

参考:
https://www.guru99.com/r-apply-sapply-tapply.html#2

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。