Skip to content
Prev 366256 / 398502 Next

Is there a funct to sum differences?

Dear Arthur,

Neither my nor Jeff Newmiller's solution uses any fancy math, just a little bit of programming. Here are the two solutions on a much larger simulated problem:
+     {
+         diffs <- matrix(0, len, maxlag)
+         for (lag in 1:maxlag){
+             diffs[1:(len - lag), lag] <- diff(x, lag=lag) 
+         }
+     }
+ )
   user  system elapsed 
   0.22    0.19    0.41
[1] -34.39477 -48.65417  33.75448  67.30261 -39.10066 204.56559
+     diffs.2 <- embed(c(x, rep(NA, maxlag)), maxlag + 1) - x
+ )
   user  system elapsed 
   0.36    0.04    0.39
[1] -34.39477 -48.65417  33.75448  67.30261 -39.10066 204.56559

My solution uses a loop, Jeff's uses the embed() function -- of which I was unaware -- which hides the loop in the function.

If you want to do this kind of simple data management in R, it helps to learn some R programming.

Best,
 John