[R] Statemement by recurrence avoiding loop

Jonathan Baron baron at cattell.psych.upenn.edu
Mon Jul 8 10:28:38 CEST 2002


On 07/08/02 09:47, tlorino at vet-alfort.fr wrote:
>Dear R users,
>
>I would like to calculate a cumulative sum as following: on the i-th row, in the
>j-th column of a matrix, I would like to obtain the sum of the (i-1) preceding elements of
>this j-th column.
>Could I avoid a "for" loop?

If the matrix is m1, then

apply(m1,1,cumsum)

does it, but the result it transformed, so if you want to put it
back so that rows in the new matrix correspond to rows in the old
matrix:

t(apply(m1,1,cumsum))

-- 
Jonathan Baron, Professor of Psychology, University of Pennsylvania
Home page:            http://www.sas.upenn.edu/~baron
R page:               http://finzi.psych.upenn.edu/
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list