SQLnRprobs
SQLnRprobs

Reputation: 77

Multiplicaton based on previous row in r

I have the following matrix

            [,1]        [,2]       [,3]        [,4]
[1,]        2532        2532       2532        2532
[2,]    1.028605846 1.541478046 1.117421996 1.001032914
[3,]    0.794723319 1.070670946 1.180653716 0.966487035
[4,]    0.869901982 1.109662803 1.020646414 1.252548365
[5,]    0.957909572 1.063494032 1.285358611 1.665068867

and am trying to loop the values through to get a final matrix of

            [,1]        [,2]        [,3]        [,4]
[1,]        2532        2532        2532        2532
[2,]    2604.430001 3903.022412 2829.312493 2534.615339
[3,]    2069.801255 4178.8527   3340.438309 2449.672862
[4,]    1800.524213 4637.117402 3409.406382 3068.33374
[5,]    1724.739379 4931.546685 4382.309851 5108.986984

I know I can use apply(data,2,prod), to get the value for the final row, but am unsure of how to loop to get values for all of the rows.

Thanks

Upvotes: 1

Views: 54

Answers (1)

romants
romants

Reputation: 3648

What you are looking for can be achieved with cumprod and apply on columns. Something like

> mat <- matrix(1:6, nrow = 3)
> mat
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6
> apply(mat, c(2), cumprod)
     [,1] [,2]
[1,]    1    4
[2,]    2   20
[3,]    6  120

Upvotes: 1

Related Questions