“*应用”家庭真的没有矢量化吗?
apply
一个常见的反射是在应用程序家族中使用一个函数。 这不是 矢量化,是循环隐藏。..Apply函数的定义中有一个for循环。lApplication函数掩埋循环,但执行时间往往与显式for循环大致相等。
apply
grep("for", capture.output(getAnywhere("apply")), value = TRUE)## [1] " for (i in 1L:d2) {" " else for (i in 1L:d2) {"
lapply
vapply
lapply## function (X, FUN, ...) ## {## FUN <- match.fun(FUN)## if (!is.vector(X) || is.object(X)) ## X <- as.list(X)## .Internal(lapply(X, FUN))## }## <bytecode: 0x000000000284b618>## <environment: namespace:base>
for
colMeans
colMeans# function (x, na.rm = FALSE, dims = 1L) # {# if (is.data.frame(x)) # x <- as.matrix(x)# if (!is.array(x) || length(dn <- dim(x)) < 2L) # stop("'x' must be an array of at least two dimensions")# if (dims < 1L || dims > length(dn) - 1L) # stop("invalid 'dims'")# n <- prod(dn[1L:dims])# dn <- dn[-(1L:dims)]# z <- if (is.complex(x)) # .Internal(colMeans(Re(x), n, prod(dn), na.rm)) + (0+1i) * # .Internal(colMeans(Im(x), n, prod(dn), na.rm))# else .Internal(colMeans(x, n, prod(dn), na.rm))# if (length(dn) > 1L) {# dim(z) <- dn# dimnames(z) <- dimnames(x)[-(1L:dims)]# }# else names(z) <- dimnames(x)[[dims + 1]]# z# }# <bytecode: 0x0000000008f89d20># <environment: namespace:base>
.Internal(colMeans(...
.Internal(lapply(..
?
sapply
colMeans
for
m <- as.data.frame(matrix(1:1e7, ncol = 1e5))system.time(colMeans(m))# user system elapsed # 1.69 0.03 1.73 system.time(sapply(m, mean))# user system elapsed # 1.50 0.03 1.60 system.time(apply(m, 2, mean))# user system elapsed # 3.84 0.03 3.90 system.time(for(i in 1:ncol(m)) mean(m[, i]))# user system elapsed # 13.78 0.01 13.93
lapply
vapply
实际上是矢量化的apply
for
lapply
青春有我