使用 tidyverse 创建一个以恒定速率增加的列

Create a column that increases at a constant rate using the tidyverse

我有一个人口时间序列,我想比较人口增长与某个增长率的关系。因此,我试图创建一个列,将我的初始人口值乘以某个恒定增长率,然后将该值乘以相同的恒定增长率,等等。我不能只使用 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递归地将你的初始值乘以你的增长率,并保留中间值。这里,.x 是您的累计值。有关详细信息,请参阅 documentation

library(ggplot2)
library(tibble)
library(dplyr)
library(purrr)

# alteratively, load the tidyverse 
# library(tidyverse)

growth_rate <- 0.05 # percent

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))

df <- df %>%
  mutate(with_purr = accumulate(population, ~ .x * (1 + growth_rate)))

df
#> # A tibble: 6 x 4
#>    year population estimated with_purr
#>   <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

为什么我们需要 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