矢量化()与应用() [英] Vectorize() vs apply()
问题描述
R
中的 Vectorize()
和 apply()
函数通常可用于实现相同的目标.出于可读性原因,我通常更喜欢对函数进行向量化,因为主要调用函数与手头的任务相关,而 sapply
则不是.当我将在我的 R 代码中多次使用该矢量化函数时,它对 Vectorize()
也很有用.例如:
The Vectorize()
and the apply()
functions in R
can often be used to accomplish the same goal. I usually prefer vectorizing a function for readability reasons, because the main calling function is related to the task at hand while sapply
is not. It is also useful to Vectorize()
when I am going to be using that vectorized function multiple times in my R code. For instance:
a <- 100
b <- 200
c <- 300
varnames <- c('a', 'b', 'c')
getv <- Vectorize(get)
getv(varnames)
对比
sapply(varnames, get)
但是,至少在 SO 上,我很少在解决方案中看到带有 Vectorize()
的示例,只有 apply()
(或它的兄弟之一).Vectorize()
是否有任何效率问题或其他合理的问题使 apply()
成为更好的选择?
However, at least on SO I rarely see examples with Vectorize()
in the solution, only apply()
(or one of it's siblings). Are there any efficiency issues or other legitimate concerns with Vectorize()
that make apply()
a better option?
推荐答案
Vectorize
只是 mapply
的包装器.它只是为您提供的任何函数构建一个 mapply
循环.因此,通常有比 Vectorize()
更容易的事情,而且显式的 *apply
解决方案最终在计算上等效或可能更好.
Vectorize
is just a wrapper for mapply
. It just builds you an mapply
loop for whatever function you feed it. Thus there are often easier things do to than Vectorize()
it and the explicit *apply
solutions end up being computationally equivalent or perhaps superior.
此外,对于您的具体示例,您听说过 mget
,对吗?
Also, for your specific example, you've heard of mget
, right?
这篇关于矢量化()与应用()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!