
Inside the C or FORTRAN code, vectors are actually processed processed using loops or a similar construct. But if you call it once, with a vector, the “figuring out” part happens just once. If you do the latter, R has to do the “figuring out” stuff, as well as the translation, each time. If you need to run a function over all the results of a vector, you could pass a whole vector through the R function to the compiled code, or you could call the R function repeatedly for each value.
#VECTOR CODE FOR R CODE#
The compiled code is able to run faster than code written in pure R, because the “figuring out” stuff is done first, and it can zoom ahead without the “translation” steps that R needs. In fft() the compiled codes only after R figures out the data type in z, and also whether to use the default value of inverse. However, R still has to interpret the input of the function before passing it to the compiled code.

These means R is calling a C, C++, or FORTRAN program to carry out operations.

If you look at their source code, it will include. R is passing the data onto a C function called C_fft. This means that R takes care of a lot of basic computer tasks for you. R is a high-level, interpreted computer language. In both cases there are three addition operations to perform. Why on earth should these take a different amount of time to calculate? Linear algebra isn’t magic. Consider a two math problems, one vectorized, and one not: But if you understand the nuts and bolts of vectorization in R, it may help you write shorter, simpler, safer, and yes, faster code in the first place.įirst, let’s acknowledge that vectorization can seem like voodoo. Other approaches, like finding a bigger machine or parallelization, could give you more bang for the buck in terms of programming time. Don’t start re-writing your code unless the time saved is going to be worth the time invested. Now, remember, premature optimization is the root of all evil (Knuth). Here, I try to explain why vectorization can be advantageous in R by showing how R works under the hood. Feedback welcome!īeginning R users are often told to “vectorize” their code. Thanks to Vince Buffalo, John Myles White, and Hadley Wickham for their input as I was preparing this.

Here are my notes from a recent talk I gave on vectorization at a Davis R Users’ Group meeting.
