mutate a resulting value on each row

Viewed 21

Hard to word the title, I can explain better what I'm trying to do with an example:

bla <- data.frame(a = c(100, 2:10))
bla
     a
1  100
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
10  10

I would like to start with 100, then multiple this column where each rows result is passed along to the next.

Tried:

> bla |> mutate(cumulative = a * lag(a))
     a cumulative
1  100         NA
2    2        200
3    3          6
4    4         12
5    5         20
6    6         30
7    7         42
8    8         56
9    9         72
10  10         90

This gets me what I want for row 2, that is 2 * 100. But not for row 3 onwards. For row 3 I wanted 3 * 200 not 3 * 2. I.e. I want the lag based on the resulting value from the previous row.

How can I do this?

0 Answers
Related