Reputation: 923
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?
Upvotes: 1
Views: 206
Reputation: 887213
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
Upvotes: 1