Why is apply() method slower than a for loop in R?

前端 未结 5 1517
既然无缘
既然无缘 2020-11-27 04:55

As a matter of best practices, I\'m trying to determine if it\'s better to create a function and apply() it across a matrix, or if it\'s better to simply loop a

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 05:35

    You can use lapply or sapply on vectors if you want. However, why not use the appropriate tool for the job, in this case ifelse()?

    > ptm <- proc.time()
    > ifelse_million <- ifelse(million > 0,1,-1)
    > proc.time() - ptm
       user  system elapsed 
      0.077   0.007   0.093 
    
    > all.equal(ifelse_million, loop_million)
    [1] TRUE
    

    And for comparison's sake, here are the two comparable runs using the for loop and sapply:

    > ptm <- proc.time()
    > apply_million <- sapply(million, squish)
    > proc.time() - ptm
       user  system elapsed 
      0.469   0.004   0.474 
    > ptm <- proc.time()
    > loop_million <- mash(million)
    > proc.time() - ptm
       user  system elapsed 
      0.408   0.001   0.417 
    

提交回复
热议问题