- library(tidyverse)
- set.seed(123)
- df = tibble(
- Year = 2002:2019,
- x1 = rnorm(18, 200, 10) |> sort(),
- x2 = rnorm(18, 1000,20) |> sort())
- df
- ## # A tibble: 18 × 3
- ## Year x1 x2
- ## <int> <dbl> <dbl>
- ## 1 2002 180. 966.
- ## 2 2003 187. 977.
- ## 3 2004 193. 979.
- ## 4 2005 194. 979.
- ## 5 2006 194. 985.
- ## 6 2007 196. 987.
- ## 7 2008 198. 991.
- ## 8 2009 201. 994.
- ## 9 2010 201. 996.
- ## 10 2011 201. 1003.
- ## 11 2012 204. 1009.
- ## 12 2013 204. 1014.
- ## 13 2014 205. 1014.
- ## 14 2015 205. 1016.
- ## 15 2016 212. 1017.
- ## 16 2017 216. 1018.
- ## 17 2018 217. 1018.
- ## 18 2019 218. 1025.
定义一个函数,计算平均增长率进而下一年的预测:
- f = function(x) {
- n = length(x)
- x[n] * (x[n] / x[1]) ^ (1/(n-1))
- }
解决问题,应用函数到每一列(除了年份),然后再拼接到原数据:
- df %>%
- bind_rows(bind_cols(Year = 2020, map_df(.[-1], f)))
- ## # A tibble: 18 × 3
- ## Year x1 x2
- ## <int> <dbl> <dbl>
- ## 1 2002 180. 966.
- ## 2 2003 187. 977.
- ## 3 2004 193. 979.
- ## 4 2005 194. 979.
- ## 5 2006 194. 985.
- ## 6 2007 196. 987.
- ## 7 2008 198. 991.
- ## 8 2009 201. 994.
- ## 9 2010 201. 996.
- ## 10 2011 201. 1003.
- ## 11 2012 204. 1009.
- ## 12 2013 204. 1014.
- ## 13 2014 205. 1014.
- ## 14 2015 205. 1016.
- ## 15 2016 212. 1017.
- ## 16 2017 216. 1018.
- ## 17 2018 217. 1018.
- ## 18 2019 218. 1025.
- ## 19 2020 220. 1029.
注:以上代码对任意多个指标列都适用。


雷达卡






京公网安备 11010802022788号







