使用用户定义的功能
用户定义的功能
用户可以根据不同程度的复杂性创建自己的功能。以下示例来自 Hadley Wickham 的 Functionals :
randomise <- function(f) f(runif(1e3))
lapply2 <- function(x, f, ...) {
out <- vector("list", length(x))
for (i in seq_along(x)) {
out[[i]] <- f(x[[i]], ...)
}
out
}
在第一种情况下,randomise 接受单个参数 f,并在 Uniform 随机变量样本上调用它。为了证明等价,我们在下面称为 set.seed:
set.seed(123)
randomise(mean)
#[1] 0.4972778
set.seed(123)
mean(runif(1e3))
#[1] 0.4972778
set.seed(123)
randomise(max)
#[1] 0.9994045
set.seed(123)
max(runif(1e3))
#[1] 0.9994045
第二个例子是 base::lapply 的重新实现,它使用函数将操作(f)应用于列表中的每个元素(x)。... 参数允许用户将其他参数传递给 f,例如 mean 函数中的 na.rm 选项:
lapply(list(c(1, 3, 5), c(2, NA, 6)), mean)
# [[1]]
# [1] 3
#
# [[2]]
# [1] NA
lapply2(list(c(1, 3, 5), c(2, NA, 6)), mean)
# [[1]]
# [1] 3
#
# [[2]]
# [1] NA
lapply(list(c(1, 3, 5), c(2, NA, 6)), mean, na.rm = TRUE)
# [[1]]
# [1] 3
#
# [[2]]
# [1] 4
lapply2(list(c(1, 3, 5), c(2, NA, 6)), mean, na.rm = TRUE)
# [[1]]
# [1] 3
#
# [[2]]
# [1] 4