Vectorize () vs apply ()

The Vectorize() and apply() functions in R can often be used to achieve the same goal. I usually prefer to vectorize a function for readability, because the main calling function is connected to the task at hand, and sapply is not. It is also useful for Vectorize() when I will use this vectorized function several times in my R code. For example:

 a <- 100 b <- 200 c <- 300 varnames <- c('a', 'b', 'c') getv <- Vectorize(get) getv(varnames) 

against

 sapply(varnames, get) 

However, at least on SO, I rarely see examples with Vectorize() in a solution, only apply() (or one of its siblings). Are there any performance issues or other legitimate issues with Vectorize() that make apply() better option?

+7
r
source share
2 answers

Vectorize is just a wrapper for mapply . It just creates a mapply for any function that you feed it. Thus, it is often simpler than Vectorize() , and explicit *apply solutions are ultimately equivalent to computing, or possibly superior.

Also, for your specific example, you heard about mget , right?

+8
source share

To add an answer to Thomas. Maybe 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) 

enter image description here

+7
source share

All Articles