I have the following working code:
x <- c(10.7, 13.0, 11.4, 11.5, 12.5, 14.1, 14.8, 14.1, 12.6, 16.0, 11.7, 10.6,
10.0, 11.4, 7.9, 9.5, 8.0, 11.8, 10.5, 11.2, 9.2, 10.1, 10.4, 10.5)
cusum <- function(x) {
s <- NA
mn <- mean(x)
for (i in seq_along(x)) {
if (i == 1)
s[i] <- 0 + x[i] - mn
else
s[i] <- s[i - 1] + x[i] - mn
}
s
}
cusum(x)
I wish to vectorize my code for performance, but I do not know how because:
- I can not use an "iterative dependency" (i.e.
s[i - 1]
to compute s[i]
) in lapply
and al.
- I can not loop over two vectors in
Reduce
(i.e. s
and x
)
How can I vectorize my function in base R? I work in a restrictive environment where I only have access to base R.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…