rloopsapplyratefpgrowth

How to use growth rates with apply function instead of a loop in R


Suppose I have a data frame 'country' with 3 colums:

My objective is to grow the GDP and population for the next five years according to assumptions. I have developped the following loop:

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

Where hypo_gdp and hypo_pop are my growth assumptions.

Is there a way to use one of the apply() functions in this case?

Thanks in advance!


Solution

  • You do not need any apply() function in this case. This is just a simple geometric progression:

    # 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