Apply ()
Apply (M,dimcode,f,fargs)
- M is a matrix.
- DimCode is the dimension number, 1 is applied to the row, and 2 is the function for the column.
- F is a function
- Fargs is an optional parameter set for F
> z <- matrix(1:6, nrow = 3)> f <- function(x) {+ x/c(2, 8)+ }> apply(z,1,f) #f函数得到两个元素,则为几行,竖着来的 [,1] [,2] [,3][1,] 0.5 1.000 1.50[2,] 0.5 0.625 0.75
Lapply ()
Lapply () (on behalf of list apply) is similar to the use of the Apply () function of the matrix, executes the given function on each component of the list, and returns another list.
list(a = 1:10, beta = exp(-3:3), logic = c(TRUE,FALSE,FALSE,TRUE))> lapply(x, mean)$a[1] 5.5$beta[1] 4.535125$logic[1] 0.5
Sapply ()
Sapply () (on behalf of simplified [l]apply) can collate the results in the form of vectors, matrices, and lists.
>Sapply (XMeanABetaLogic 5.500000 4.535125 0.500000 >Sapply (Xquantile) #每一个对应组件输出5个元素, so for 5 rows, like a matrix, vertical.ABetalogic0% 1.00 0.04978707 0.25% 3.25 0. 25160736 0. 050% 5. 1. 00000000 0. 575% 7. 5. 05366896 1.0100%. 08553692 1.0> sapply (2: 4, seq)[[1]][1] 1 2[[2]][1] 1 2 3[[3]][1] 1 2 3 4
Vapply ()
Vapply () is similar to sapply () in that he can pre-specify the return value type. Make the resulting results more secure.
>Vapply (XQuantileC (1,2,5,6,8)) #它需要一个5个长度的向量来告诉他返回的类型, the contents of the vector can be transformed a beta logic0% 1. 0. 04978707 0. 02 5% 3.0. 25160736 0. 050% 5. 1. 00000000 0. 575% 7.5. 05366896 1. 100% 10< c16>.00. 08553692 1. 0
Tapply ()
Tapply (x,f,g) requires vector x (x cannot be a data frame), factor or factor list F, function G.
Tapply () performs the following actions: Grouping by F pair X, running function g on the grouped vector
> a <- c(24,25,36,37)> b <- c(‘q‘, ‘w‘, ‘q‘,‘w‘)> tapply(a, b, mean) q w 30 31
Mapply ()
Multi-parameter version of Sapply (). The first time to calculate the first element of the vector into each group to the fun, to settle the results, the second pass through the second element of the group vector, get the result; the third element of each group vector is passed ... And so on
list(a = c(1:10), b = c(11:20))l2 <- list(c = c(21:30), d = c(31:40))mapply(sum, l1$a, l1$b, l2$c, l2$d)## [1] 64 68 72 76 80 84 88 92 96 100
Ref:https://www.cnblogs.com/xihehe/p/7473981.html
R language Apply,sapply,lapply,tapply,vapply, the use of mapply