【问题标题】:Create a column that increases at a constant rate using the tidyverse使用 tidyverse 创建一个以恒定速率增加的列
【发布时间】:2018-03-28 19:56:09
【问题描述】:

我有一个人口的时间序列,我想比较人口的增长与某个增长率的关系。因此,我试图创建一个列,将我的初始人口值乘以某个恒定增长率,然后将该值乘以相同的恒定增长率,等等。我不能只使用 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))

【问题讨论】:

    标签: r dplyr tidyverse purrr


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      使用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
      

      【讨论】:

      • 也许你已经知道这一点,但如果你的增长率是恒定的,就像这里,那么1.05^(row_number()-1),如果不是cumprod(growth_rate_vector)...
      • 如果您一开始就规定 growth_rate 为 1.05,这不是更有意义吗?
      猜你喜欢
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 2023-02-03
      • 2021-10-25
      • 1970-01-01
      • 2015-08-13
      相关资源
      最近更新 更多