Skip to content
Prev 79198 / 398503 Next

Ways to speed up R code?

ecoinfo wrote:
- As you found, indexing operations on matrices are much faster than on 
dataframes.

- Avoid growing allocations:  calculate the size you need, then allocate 
it all at once.

- Vectorize calculations.

- Use Rprof() to identify where your code is spending its time, and 
concentrate your efforts on that area.  Perhaps translate some essential 
routines into compiled C or Fortran.

- For a smaller improvement that might not suit your application, 
convert factors to their numeric codes.

- Break up long calculations into smaller pieces, so you can write out 
intermediate values.  This doesn't necessarily speed it up, but it lets 
you stop and restart the calculation.  It may also make it more suited 
to running on a cluster of computers instead of just one.

- Limit your use of memory so you don't end up using a swap file.  Do 
this by only keeping objects that will be used later, removing others. 
(With the size of objects you were working with this may not be an issue.)

Duncan Murdoch