Suppose I have a vector v
of length n
; I wish to create a new vector of that length, that will contain NA
in the first k
cells, and that in cell number m
it will contain the difference v[m]-v[m-k]
.
I can create a for-loop that accomplishes that task:
diffs <- rep(NA, length(v))
for (i in k+1:length(diffs)) {
diffs[i] <- v[i] - v[i-k]
}
But I've heard loops in R
are slow, and it looks a bit cumbersome to do it like that.
Actually, my goal is to create a list of diff vectors and not a single one - one for each k
in some range. Are loops the only solution?
Example
On the input v <- 1:5
and k=2
I'd expect the output [1] NA NA 2 2 2
(however, as it turns out, the output of my snippet above is [1] NA NA 2 2 2 NA NA
...)