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: There is a function called Map
的函数,可能类似于其他语言的地图:
lapply
返回与X相同长度的列表,其中每个元素都是将FUN应用于X的对应元素的结果。
do.call
构造并执行函数调用,从一个名称或一个函数以及要传递给的参数列表
Map 将函数应用于给定向量的相应元素...
Map
是对 mapply
的简单包装,它不会试图简化结果,类似于Common Lisp的mapcar(参数被回收,然而)。未来的版本可能允许对结果类型进行一些控制。
$ ol b $ b Map 是
mapply
在许多情况下,Map
和 lapply
类似。
lapply
:
lapply(虹膜,class)
$ Sepal.Length
[1]numeric
$ Sepal.Width
[1]numeric
$ Petal.Length
[1]numeric
$ Petal.Width
[1]numeric
$物种
[1]factor
Map
$ b $ pre code $ Map $ {
$ Sepal.Length
[1] numeric
$ Sepal.Width
[1]numeric
$ Petal.Length
[1]numeric
$ Petal.Width
[1]numeric
$物种
[1]factor
do.call
将函数作为输入并将其他参数泼溅到函数中。例如,它被广泛用于将列表组装成更简单的结构(通常使用 rbind
或 cbind
)。例如:
x < - lapply(iris,class)
do.call(c,x)
Sepal.Length Sepal.Width Petal.Length Petal.Width种类
数字数字数字数字因子
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
that may be similar to map in other languages:
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
constructs and executes a function call from a name or a function and a list of arguments to be passed to it.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
is a wrapper aroundmapply
lapply
is a special case ofmapply
- Therefore
Map
andlapply
will be similar in many cases.
For example, here is lapply
:
lapply(iris, class)
$Sepal.Length
[1] "numeric"
$Sepal.Width
[1] "numeric"
$Petal.Length
[1] "numeric"
$Petal.Width
[1] "numeric"
$Species
[1] "factor"
And the same using 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
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
).
For example:
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屋!