[英]How to create a function and a loop to calculate growth rates of variables in a data frame in R
[英]How to use growth rates with apply function instead of a loop in R
假设我有一个包含3个列的“国家”数据框:
我的目标是根据假设在未来五年内增加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()函数?
提前致谢!
在这种情况下,您不需要任何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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.