【问题标题】:How to use growth rates with apply function instead of a loop in R如何使用应用函数而不是 R 中的循环来使用增长率
【发布时间】:2018-05-19 18:01:24
【问题描述】:

假设我有一个包含 3 列的数据框“国家”:

  • 年(从 2000 年到 2017 年)
  • 国内生产总值
  • 人口

我的目标是根据假设在未来五年内增加 GDP 和人口。我开发了以下循环:

country[19:23,1] <- seq(2018, by=1, length.out = 5) 

for (i in 19:nrow(country)){
  country[i,"GDP"] <- country[i-1, "GDP"] * (1 + hypo_gdp/100)
  country[i,"Population"] <- country[i-1, "Population"] * (1 + hypo_pop/100)
}

hypo_gdp 和 hypo_pop 是我的增长假设。

有没有办法在这种情况下使用其中一个 apply() 函数?

提前致谢!

【问题讨论】:

    标签: r loops apply rate fpgrowth


    【解决方案1】:

    在这种情况下,您不需要任何 apply() 函数。这只是一个简单的几何级数:

    # simulate some data
    country <- data.frame(year = 2000:2017, 
                          GDP = rep(100, 18), 
                          Population = rep(1000, 18))
    
    country[19:23,1] <- seq(2018, by=1, length.out = 5) 
    
    # define gdp and pop parameters
    hypo_gdp = 5
    hypo_pop = 2
    
    # define common ratios
    b1 <- (1 + hypo_gdp/100)
    b2 <- (1 + hypo_pop/100)
    
    # calculate values for years 2018-2022
    country[19:23,2] =  country$GDP[18]* b1 ^ (1:5)
    country[19:23,3] =  country$Population[18]* b2 ^ (1:5)
    tail(country)
    #    year      GDP Population
    # 18 2017 100.0000   1000.000
    # 19 2018 105.0000   1020.000
    # 20 2019 110.2500   1040.400
    # 21 2020 115.7625   1061.208
    # 22 2021 121.5506   1082.432
    # 23 2022 127.6282   1104.081
    

    【讨论】:

      猜你喜欢
      • 2020-11-20
      • 1970-01-01
      • 2013-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多