How could I avoid for loop calculating xts weighted sum as I am trying to do below:
library(xts)
thetaSum <- function(theta, w=c(1, 1, 1)) {
sum(coredata(theta)*rev(w))
}
n <- 10
tmpVec <- rep(1, n)
tmpDates <- seq(as.Date("2000-01-01"), length = n, by = "day")
theta <- xts(tmpVec, order.by=tmpDates)
N <- 3
thetaSummed <- xts(rep(NA, n), order.by=tmpDates)
for (i in N:n) {
thetaTemp <- theta[(i-N+1):i, ]
thetaSummed[i] <- thetaSum(thetaTemp, w=rep(1, N))
}
thetaSummed
N is a look back period smaller than n.
What are some fast alternatives for for loop?
You can use
rollapply.