lapply 和 do.call 有什么区别? [英] What's the difference between lapply and do.call?
问题描述
我最近在学习 R,被两个函数搞糊涂了:lapply
和 do.call
.看起来它们只是类似于 Lisp 中的 map
函数.但是为什么有两个函数名称如此不同呢?为什么 R 不直接使用名为 map
的函数?
I'm learning R recently and confused by two function: lapply
and do.call
. It seems that they're just similar to map
function in Lisp. But why are there two functions with such a different name? Why doesn't R just use a function called map
?
推荐答案
有一个函数叫做Map
,可能和其他语言的map类似:
There is a function called Map
that may be similar to map in other languages:
lapply
返回一个与 X 长度相同的列表,其中的每个元素都是对 X 的对应元素应用 FUN 的结果.
lapply
returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X.
do.call
根据名称或函数以及要传递给它的参数列表构造并执行函数调用.
do.call
constructs and executes a function call from a name or a function and a list of arguments to be passed to it.
Map
将函数应用于给定向量的相应元素... Map
是 mapply
的简单包装器,它执行不试图简化结果,类似于 Common Lisp 的 mapcar(但是参数被回收).未来的版本可能允许对结果类型进行一些控制.
Map
applies a function to the corresponding elements of given vectors... Map
is a simple wrapper to mapply
which does not attempt to simplify the result, similar to Common Lisp's mapcar (with arguments being recycled, however). Future versions may allow some control of the result type.
Map
是对mapply
的封装lapply
是mapply
的特例- 因此
Map
和lapply
在很多情况下是相似的.
Map
is a wrapper aroundmapply
lapply
is a special case ofmapply
- Therefore
Map
andlapply
will be similar in many cases.
例如,这里是lapply
:
lapply(iris, class)
$Sepal.Length
[1] "numeric"
$Sepal.Width
[1] "numeric"
$Petal.Length
[1] "numeric"
$Petal.Width
[1] "numeric"
$Species
[1] "factor"
同样使用Map
:
Map(class, iris)
$Sepal.Length
[1] "numeric"
$Sepal.Width
[1] "numeric"
$Petal.Length
[1] "numeric"
$Petal.Width
[1] "numeric"
$Species
[1] "factor"
<小时>
do.call
将一个函数作为输入并将其其他参数散布给该函数.它被广泛使用,例如,将列表组装成更简单的结构(通常使用 rbind
或 cbind
).
do.call
takes a function as input and splatters its other arguments to the function. It is widely used, for example, to assemble lists into simpler structures (often with rbind
or cbind
).
例如:
x <- lapply(iris, class)
do.call(c, x)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
"numeric" "numeric" "numeric" "numeric" "factor"
这篇关于lapply 和 do.call 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!