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

前端 未结 5 1511
既然无缘
既然无缘 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:46

    The point of the apply (and plyr) family of functions is not speed, but expressiveness. They also tend to prevent bugs because they eliminate the book keeping code needed with loops.

    Lately, answers on stackoverflow have over-emphasised speed. Your code will get faster on its own as computers get faster and R-core optimises the internals of R. Your code will never get more elegant or easier to understand on its own.

    In this case you can have the best of both worlds: an elegant answer using vectorisation that is also very fast, (million > 0) * 2 - 1.

提交回复
热议问题