本文介绍了Vectorize()与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)

vs

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?

这篇关于Vectorize()与Apply()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 03:28