How to create a new column in data frame which each row of new column is multiplication of all previous rows

南笙酒味 提交于 2021-02-10 17:56:45

问题


I have a data frame like the one shown below:

ref_inf <- c(2,3,1,2.2,1.3,1.5,1.9,1.8,1.9,1.9)
ref_year<- seq(2001,2010)
inf_data <- data.frame(ref_year,ref_inf)

   ref_year ref_inf
1      2001     2.0
2      2002     3.0
3      2003     1.0
4      2004     2.2
5      2005     1.3
6      2006     1.5
7      2007     1.9
8      2008     1.8
9      2009     1.9
10     2010     1.9

What I want to do is to create a new column "Final Inflation" and each number in the new column should be calculated by multiplying all previous numbers in ref_inf column, so for example, if I want to calculate Final Inflation for the year 2005 I should do this:

Final inflation= (1+1.3/100)*(1+2.2/100)*(1+1.0/100)*(1+3.0/100)*(1+2.0/100)

or as another example, Final inflation for the year 2003 would be

Final inflation= (1+1.0/100)*(1+3.0/100)*(1+2.0/100)

I should do this calculation for each row of the data frame

How can I do that using dplyr in R?


回答1:


We could use cumprod

library(dplyr)
inf_data %>% 
    mutate(new = cumprod(1 + ref_inf/100))

-output

#  ref_year ref_inf      new
#1      2001     2.0 1.020000
#2      2002     3.0 1.050600
#3      2003     1.0 1.061106
#4      2004     2.2 1.084450
#5      2005     1.3 1.098548
#6      2006     1.5 1.115026
#7      2007     1.9 1.136212
#8      2008     1.8 1.156664
#9      2009     1.9 1.178640
#10     2010     1.9 1.201035


来源:https://stackoverflow.com/questions/65172199/how-to-create-a-new-column-in-data-frame-which-each-row-of-new-column-is-multipl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!