Getting a vector of differences of a vector

2019-08-06 20:07发布

问题:

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...)

回答1:

?diff

vec <- data.frame(v=c(1,3,5,15,21))
vec$dif <- c(NA, diff(vec$v, lag = 1, differences = 1))

> vec
   v dif
1  1  NA
2  3   2
3  5   2
4 15  10
5 21   6

For other lag interval or magnitude of differences, change lag and differences arguments accordingly



标签: r vector