[R] inverse cumsum
Wacek Kusnierczyk
Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Wed Jun 18 14:30:47 CEST 2008
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
More information about the R-help
mailing list