R语言基础

apply(), lapply(), sapply(), tap

2020-06-28  本文已影响0人  生信编程日常

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

上一篇 下一篇

猜你喜欢

热点阅读