Vectorize()vs apply()(Vectorize() vs apply())

编程入门 行业动态 更新时间:2024-10-22 23:47:58
Vectorize()vs apply()(Vectorize() vs apply())

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?

更多推荐

本文发布于:2023-07-25 22:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1267202.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Vectorize   apply

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!