Skip to content
Prev 366255 / 398502 Next

Is there a funct to sum differences?

Hello John,


Here I am back again. Having learned no maths yet but I've looked over the
results here and they are what I am after.

Now I'll try to understand how you did it.

:)




----- Original Message -----
From: "Fox, John" <jfox at mcmaster.ca>
To: arthur brogard <abrogard at yahoo.com>
Cc: Jeff Newmiller <jdnewmil at dcn.davis.ca.us>; "r-help at r-project.org" <r-help at r-project.org>
Sent: Sunday, 25 December 2016, 0:55
Subject: RE: [R] Is there a funct to sum differences?

Dear Arthur,

Here's a simple script to do what I think you want. I've applied it to a contrived example, a vector of the squares of the integers 1 to 25, and have summed the first 5 differences, but the script is adaptable to any numeric vector and any maximum lag. You'll have to decide what to do with the last maximum-lag (in my case, 5) entries:

-------------- snip ------------
[1]   1   4   9  16  25  36  49  64  81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576
[25] 625
+     diffs[1:(len - lag), lag] <- diff(x, lag=lag)
+ }
[,1] [,2] [,3] [,4] [,5]
[1,]    3    8   15   24   35
[2,]    5   12   21   32   45
[3,]    7   16   27   40   55
[4,]    9   20   33   48   65
[5,]   11   24   39   56   75
[6,]   13   28   45   64   85
[,1] [,2] [,3] [,4] [,5]
[20,]   41   84  129  176  225
[21,]   43   88  135  184    0
[22,]   45   92  141    0    0
[23,]   47   96    0    0    0
[24,]   49    0    0    0    0
[25,]    0    0    0    0    0
[1]  85 115 145 175 205 235 265 295 325 355 385 415 445 475 505 535 565 595 625 655 450 278 143  49
[25]   0
-------------- snip ------------

The script could very simply be converted into a function if this is a repetitive task with variable inputs.

I hope this helps,
John

-----------------------------
John Fox, Professor
McMaster University
Hamilton, Ontario
Canada L8S 4M4
Web: socserv.mcmaster.ca/jfox