[R] Cumulative row sums, row differences

glen_b
2009-07-28T06:00:42Z

I tried searching but I couldn't quite find what I was looking for.

Here's a dummy data matrix (with row and column
labels):
> y
   0 1  2 3  4
21 3 4  8 5  5
22 3 6  8 6 NA
23 4 5 11 4  3
24 4 2  1 4  6
25 6 4  4 6  6

I can get cumulative row sums as follows:
> cy<-t(apply(y,1,cumsum))
> cy
   0  1  2  3  4
21 3  7 15 20 25
22 3  9 17 23 NA
23 4  9 20 24 27
24 4  6  7 11 17
25 6 10 14 20 26

Which works, but this seems rather clumsy, especially the need for t().

Is there a better way? One that still retains row and/or column labels?
(that will also work for data frames, if possible - though of course one can
always as.data.frame() )

Row differences present a different problem. Here's one way to get back the
original data:

> cbind(cy[,1],cy[,-1]-cy[,-nrow(cy)])
     1  2 3  4
21 3 4  8 5  5
22 3 6  8 6 NA
23 4 5 11 4  3
24 4 2  1 4  6
25 6 4  4 6  6

However, if I use that I lose the first column label. Is there a way to do
something like this without
losing that label? (again, if possible, that also works for data frames?)

thanks!

Glen_B.

--
View this message in context:
http://www.nabble.com/Cumulative-row-sums%2C-row-differences-tp24692986p24692986.html
Sent from the R help mailing list archive at Nabble.com.