r - Getting a vector of differences of a vector -
suppose have vector v of length n; wish create new vector of length, contain na in first k cells, , in cell number m contain difference v[m]-v[m-k].
i can create for-loop accomplishes task:
diffs <- rep(na, length(v)) (i in k+1:length(diffs)) { diffs[i] <- v[i] - v[i-k] } but i've heard loops in r slow, , looks bit cumbersome that.
actually, goal create list of diff vectors , not single 1 - 1 each k in range. loops solution?
example
on input v <- 1:5 , k=2 i'd expect output [1] na na 2 2 2 (however, turns out, output of snippet above [1] na na 2 2 2 na na...)
?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 , differences arguments accordingly
Comments
Post a Comment