The key is line 9. Here, we are updatingsm, by subtracting the oldest
element making up the sum (x[i-1]) and adding the new one (x[i+k-1]).
Yet another approach to this problem is to use the R functioncumsum(),
which forms cumulative sums from a vector. Here is an example:
> y <- c(5,2,-3,8)
> cumsum(y)
[1]57412
Here, the cumulative sums ofyare5=5,5+2=7,5+2+(−3)=4,and
5+2+(−3)+8=12,thevalues returned bycumsum().
The expressionsum(x[i:(i+(k-1))inpreda()in the example suggests
using differences ofcumsum()instead:
predc <- function(x,k) {
n <- length(x)
k2 <- k/2
# the vector red will contain our predicted values
pred <- vector(length=n-k)
csx <- c(0,cumsum(x))
for (i in 1:(n-k)) {
if (csx[i+k] - csx[i] >= k2) pred[i] <- 1 else pred[i] <- 0
}
return(mean(abs(pred-x[(k+1):n])))
}
Instead of applyingsum()to a window ofkconsecutive elements inx,
like this:
sum(x[i:(i+(k-1))
we compute that same sum by finding the difference between the cumulative
sums at the end and beginning of that window, like this:
csx[i+k] - csx[i]
Note the prepending ofa0inthevector of cumulative sums:
csx <- c(0,cumsum(x))
This is needed in order to handle the casei=1correctly.
This approach inpredc()requires just one subtraction operation per
iteration of the loop, compared to two inpredb().
2.6 Vectorized Operations......................................................
Suppose we have a functionf()that we wish to apply to all elements of a vec-
torx. In many cases, we can accomplish this by simply callingf()onxitself.
Vectors 39