我有一个时间序列的人口,我想比较人口相对于某些增长率的增长方式。因此,我试图创建一个将初始人口值乘以某个恒定增长率,然后将该值乘以相同的恒定增长率等的列。等等。我不能仅仅使用mutate乘以增长率因为它不会使用以前的值。
注意:我已经在下面回答了我自己的问题,但已将其作为资源提供给其他人。如果还有其他方法可以实现相同的目标,那么我将对此感兴趣。
library(ggplot2)
library(tibble)
library(dplyr)
growth_rate <- 0.05 # percent
# the "estimated" column is what I want.
df <- tibble(year = seq(2000, 2005, by = 1),
population = seq(1, 2, length = 6),
estimated = c(1.00, 1.05, 1.10, 1.16, 1.22, 1.28))
purrr::accumulate
当使用以下简单公式可以实现相同的目的时,为什么需要:
library(tidyverse)
growth_rate <- 0.05 # percent
df %>% mutate(Calculated = first(estimated)*((1+growth_rate)^(row_number()-1)))
# # A tibble: 6 x 4
# year population estimated Calculated
# <dbl> <dbl> <dbl> <dbl>
# 1 2000 1.00 1.00 1.00
# 2 2001 1.20 1.05 1.05
# 3 2002 1.40 1.10 1.10
# 4 2003 1.60 1.16 1.16
# 5 2004 1.80 1.22 1.22
# 6 2005 2.00 1.28 1.28
编辑
@Frank已经在上面的答案之一中指出了comment
使用复合利率进行计算growth_rate
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句