Re: [R] inverse cumsum

From: Wacek Kusnierczyk <Waclaw.Marcin.Kusnierczyk_at_idi.ntnu.no>
Date: Wed, 18 Jun 2008 14:30:47 +0200

Gavin Simpson wrote:
>
>> rc = nrow(m)
>> cumsums = apply(m[rc:1,], 2, cumsum)[rc:1,]
>>
>
> Alternatively, just use rev() instead of doing it by hand:
>
>
>
>> cs2 <- apply(dat, 2, function(x) {rev(cumsum(rev(x)))})
>>
yes, that's more elegant, but somewhat less efficient:

m = matrix(1:100000, 100, 100)
system.time(for (i in 1:1000) {rc=nrow(m); apply(m[rc:1,], 2, cumsum)[rc:1,]})
# user system elapsed
# 1.981 0.000 1.983
system.time(for (i in 1:1000) apply(m, 2, function(x) rev(cumsum(rev(x)))) # user system elapsed
# 4.816 0.016 4.833
system.time({revcumsum=function(x) rev(cumsum(rev(x))); for (i in 1:1000) apply(m, 2, revcumsum)})
# user system elapsed
# 4.824 0.036 4.866

vQ



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. Received on Wed 18 Jun 2008 - 13:31:27 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 18 Jun 2008 - 16:30:47 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive