Vectorize() vs apply()

和自甴很熟 提交于 2019-11-29 01:45:57

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?

To add to Thomas's answer. Maybe also speed?

    # install.packages(c("microbenchmark", "stringr"), dependencies = TRUE)
require(microbenchmark)
require(stringr)

Vect <- function(x) { getv <- Vectorize(get); getv(x) }
sapp <- function(x) sapply(x, get)
mgett <- function(x) mget(x)
res <- microbenchmark(Vect(varnames), sapp(varnames), mget(varnames), times = 15)

## Print results:
print(res)
Unit: microseconds
           expr     min       lq  median       uq     max neval
 Vect(varnames) 106.752 110.3845 116.050 122.9030 246.934    15
 sapp(varnames)  31.731  33.8680  36.199  36.7810 100.712    15
 mget(varnames)   2.856   3.1930   3.732   4.1185  13.624    15


### Plot results:
boxplot(res)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!