Vectorize() vs apply()

后端 未结 2 380
太阳男子
太阳男子 2020-12-15 23:17

The Vectorize() and the apply() functions in R can often be used to accomplish the same goal. I usually prefer vectorizing a function

相关标签:
2条回答
  • 2020-12-15 23:54

    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)
    

    enter image description here

    0 讨论(0)
  • 2020-12-16 00:04

    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?

    0 讨论(0)
提交回复
热议问题