包括函数:lapply, sapply, vapply
lapply
该函数会返回一个长度和X参数的长度相同的列表,其中每个元素都是X参数在FUN函数作用下的结果。
实现源码
1 2 3 4 5 6 7
| function (X, FUN, ...) { FUN <- match.fun(FUN) if (!is.vector(X) || is.object(X)) X <- as.list(X) .Internal(lapply(X, FUN)) }
|
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| > a [,1] [,2] [1,] 1 3 [2,] 2 4 > lapply(a, function(x)x^2) # length(a) == 4 [[1]] [1] 1 [[2]] [1] 4 [[3]] [1] 9 [[4]] [1] 16 > d $a [1] 1 2 $b [1] 3 4 5 > lapply(d, sum) # length(d) == 2 $a [1] 3 $b [1] 12
|
一个实际的例子:一次性加载某个目录下的R文件
1 2 3 4 5 6
| CaiSource <- function(x, p.path) { source(paste(p.path, x, sep="")) } lapply(list.files(path=lib.path, pattern='\\.[rR]$'), CaiSource, lib.path)
|
sapply
1
| sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)
|
sapply是对lapply的封装,实现代码:
1 2 3 4 5 6 7 8 9 10
| function (X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE) { FUN <- match.fun(FUN) answer <- lapply(X = X, FUN = FUN, ...) if (USE.NAMES && is.character(X) && is.null(names(answer))) names(answer) <- X if (!identical(simplify, FALSE) && length(answer)) simplify2array(answer, higher = (simplify == "array")) else answer }
|
vapply
1
| vapply(X, FUN, FUN.VALUE, ..., USE.NAMES = TRUE)
|
该函数和sapply类似
1 2 3 4 5 6 7
| function (X, FUN, FUN.VALUE, ..., USE.NAMES = TRUE) { FUN <- match.fun(FUN) if (!is.vector(X) || is.object(X)) X <- as.list(X) .Internal(vapply(X, FUN, FUN.VALUE, USE.NAMES)) }
|
FUN.VALUE的值定义是?