Multiply previous row value by constant R

前端 未结 2 1543
南笙
南笙 2020-12-20 21:07

Have a simple R question but cannot seem to find an answer:

I have a data frame like this:

assumption_val year
1.2            2015
0              201         


        
相关标签:
2条回答
  • 2020-12-20 21:46

    You are looking for cumprod:

    cumprod(rep(1.2, 5))
    

    Like its better known friend, cumsum, it accumulates past results, but it performs a multiplication rather than addition.

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

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

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

    A nice feature of this method is that you can adjust the growth rate in each period. For instance if you wanted to start at 1.5 rather than 1.2, you would 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)))
    
    0 讨论(0)
  • 2020-12-20 21:46
    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
    
    0 讨论(0)
提交回复
热议问题