Book Image

R High Performance Programming

Book Image

R High Performance Programming

Overview of this book

Table of Contents (17 chapters)
R High Performance Programming
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Compiling R code before execution


In Chapter 1, Understanding R's Performance – Why Are R Programs Sometimes Slow? we saw how R, being an interpreted language, has to parse and evaluate code every time an R program is run. This takes a lot of CPU time and slows down the execution of R programs. R provides the compiler package to somewhat reduce this issue. The functions in this package allow us to compile R code beforehand and save R a step or two when we execute the code. Let's see how this works.

Compiling functions

Let's define a mov.avg() function that calculates the moving average of a numeric series:

# Compute the n-period moving average of x
mov.avg <- function(x, n=20) {
    total <- numeric(length(x) - n + 1)
    for (i in 1:n) {
        total <- total + x[i:(length(x) - n + i)]
    }
  total / n
}

Given a numeric vector x and period n, we first calculate the n element's window sum of the elements of x. For example, if x is [1, 2, 1, 3, 5] and n is 2, then we calculate total...