R中的Vectorize()和apply()函数通常可用于实现相同的目标。 为了可读性的原因,我通常更喜欢矢量化函数,因为主调用函数与当前的任务相关,而sapply则不是。 对于Vectorize() ,我将在R代码中多次使用该矢量化函数也很有用。 例如:
a <- 100 b <- 200 c <- 300 varnames <- c('a', 'b', 'c') getv <- Vectorize(get) getv(varnames)VS
sapply(varnames, get)但是,至少在这个问题上,我很少在解决方案中看到Vectorize()例子,只有apply() (或者它的一个兄弟)。 Vectorize()是否存在效率问题或其他合理问题,使apply()成为更好的选择?
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)vs
sapply(varnames, get)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解决方案最终在计算上等同于或可能是优越的。
另外,对于你的具体例子,你听说过mget ,对吧?
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.
Also, for your specific example, you've heard of mget, right?
更多推荐
发布评论