如何在数据框中创建新列,其中新列的每一行都是所有先前行的乘积 [英] How to create a new column in data frame which each row of new column is multiplication of all previous rows

查看: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

我想做的是创建一个新的最终通货膨胀"列.并且新列中的每个数字都应通过将ref_inf列中的所有先前数字相乘来计算,因此,例如,如果我要计算 2005 年的最终通货膨胀,我应该这样做:

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)

或作为另一个示例, 2003 年的最终通货膨胀将

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

我该如何在R中使用 dplyr ?

推荐答案

我们可以使用 cumprod

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

-输出

#  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

这篇关于如何在数据框中创建新列,其中新列的每一行都是所有先前行的乘积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆