Multiply the value of the previous row by the constant R

Have a simple R question, but can't find the answer:

I have a data frame like this:

assumption_val year 1.2 2015 0 2016 0 2017 0 2018 0 2019 

I want to grow each value 20% more than the previous year in order to output something like this:

 assumption_val year 1.2 2015 1.44 2016 1.73 2017 2.07 2018 2.49 2019 

How can I refer to the previous line and multiply it by 1.2 to achieve this?

Thanks!

+5
source share
2 answers

You are looking for cumprod :

 cumprod(rep(1.2, 5)) 

Like his more famous friend, cumsum , he accumulates past results, but performs multiplication, not addition.

 df <- data.frame(assumption_val=cumprod(rep(1.2, 5)), years=2015:2019) 

A good generalization of these functions is Reduce . For example, here Reduce performs this calculation. You can replace "*" with "+" and have cumsum .

 Reduce("*", rep(1.2, 5), accumulate = T) 

A good feature of this method is that you can adjust the growth rate in each period. For example, if you want to start with 1.5, not 1.2, you simply adjust your growth vector to c(1.5, rep(1.2, 4)) to calculate the new growth as follows:

 cumprod(c(1.5, rep(1.2, 4))) 
+5
source
 data <- read.table(textConnection(" assumption_val year 1.2 2015 0 2016 0 2017 0 2018 0 2019"), header = TRUE) data$assumption_val <- data$assumption_val[1]^(1:nrow(data)) data ## assumption_val year ## 1 1.20000 2015 ## 2 1.44000 2016 ## 3 1.72800 2017 ## 4 2.07360 2018 ## 5 2.48832 2019 
+2
source

All Articles