Why are loops slow in R?

前端 未结 4 1934
日久生厌
日久生厌 2020-11-22 15:05

I know that loops are slow in R and that I should try to do things in a vectorised manner instead.

But, why? Why are loops slow and apply i

4条回答
  •  抹茶落季
    2020-11-22 15:48

    It's not always the case that loops are slow and apply is fast. There's a nice discussion of this in the May, 2008, issue of R News:

    Uwe Ligges and John Fox. R Help Desk: How can I avoid this loop or make it faster? R News, 8(1):46-50, May 2008.

    In the section "Loops!" (starting on pg 48), they say:

    Many comments about R state that using loops is a particularly bad idea. This is not necessarily true. In certain cases, it is difficult to write vectorized code, or vectorized code may consume a huge amount of memory.

    They further suggest:

    • Initialize new objects to full length before the loop, rather than increasing their size within the loop.
    • Do not do things in a loop that can be done outside the loop.
    • Do not avoid loops simply for the sake of avoiding loops.

    They have a simple example where a for loop takes 1.3 sec but apply runs out of memory.

提交回复
热议问题