-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
R High Performance Programming
By :
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.
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...
Change the font size
Change margin width
Change background colour