[R] inverse cumsum

Erich Neuwirth erich.neuwirth at univie.ac.at
Wed Jun 18 14:04:13 CEST 2008


You did not specify exactly what you mean by the inverse of cumsum.
If you want (in pseudocode)
cumsumfromright(a)(k):=(sum(a(i),i=k..length(a))
giving you the sums over the tails of the sequence, then
cumsumfromright <- function(x) rev(cumsum(rev(x)))
is probably what you want.
If you want to find the sequence which has a given sequence a as its 
cumsum, you want

firstdiff <- function(x) {
   shifted <- c(0,x[1:(length(x)-1)])
   x-shifted
   }


With this function,

cumsum(firstdiff(x)) == x and
firstdiff(cumsum(x)) == x

for every numeric vector x.


(Ted Harding) wrote:
> On 18-Jun-08 10:17:09, Alfredo Alessandrini wrote:
>> I've a matrix like this:
>>
>> 1985     1.38     1.27     1.84     2.10     0.59     3.47
>> 1986     1.05     1.13     1.21     1.54     0.21     2.14
>> 1987     1.33     1.21     1.77     1.44     0.27     2.85
>> 1988     1.86     1.06     2.33     2.14     0.55     1.40
>> 1989     2.10     0.65     2.74     2.43     1.19     1.45
>> 1990     1.55     0.00     1.59     1.94     0.99     2.14
>> 1991     0.92     0.72     0.50     1.29     0.54     1.22
>> 1992     2.15     1.28     1.23     2.26     1.22     3.17
>> 1993     1.50     0.87     1.68     1.97     0.83     2.55
>> 1994     0.69     0.00     0.76     1.89     0.60     0.87
>> 1995     1.13     1.04     1.19     1.52     1.13     1.78
>>
>> Can I utilise a cumsum inverse? from 1995 to 1985?
>>
>> Thank you,
>> Alfredo
> 
> Try on the lines of:
> 
>   cumsum(c(1,2,3,4,5))
> # [1]  1  3  6 10 15
>   cumsum(rev(c(1,2,3,4,5)))
> # [1]  5  9 12 14 15
> 
> Hoping this helps,
> Ted.
> 
> --------------------------------------------------------------------
> E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
> Fax-to-email: +44 (0)870 094 0861
> Date: 18-Jun-08                                       Time: 11:50:40
> ------------------------------ XFMail ------------------------------
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 
> 

-- 
Erich Neuwirth, University of Vienna
Faculty of Computer Science
Computer Supported Didactics Working Group
Visit our SunSITE at http://sunsite.univie.ac.at
Phone: +43-1-4277-39464 Fax: +43-1-4277-39459



More information about the R-help mailing list