'How to compute the growth rate of a variable for a varying time horizon in a panel? [closed]
I'm trying to calculate the growth rate of the gdp per capita(pib_pc) for 32 states in a time horizon of 40 years but the time horizon changes. For example, in the first row I would like to get the growth rate of pib_pc between 1980 and 2017 for state i, in the second row the growth rate between 1981 and 2017 for state i and so on for each year and state.
Attached an image of how my panel looks like: The panel
So far I have been able to compute the growth rates of pib_pc for 5 and 10 year horizon using mutate and lead from the package dplyr. Here's the code:
data <- data %>%
group_by(estado) %>%
mutate(g_10 = (dplyr::lead(pib_pc,10)-pib_pc)/pib_pc) %>%
mutate(g_15 = (dplyr::lead(pib_pc,15)-pib_pc)/pib_pc) %>%
ungroup()
Solution 1:[1]
Are you looking for something like this?
library(dplyr)
data <- data.frame(
state = rep(c('Aguascalientes', 'Jalisco'), each = 10),
year = 2011:2020,
population = 91:100,
gdp = 100:109
)
data
#> state year population gdp
#> 1 Aguascalientes 2011 91 100
#> 2 Aguascalientes 2012 92 101
#> 3 Aguascalientes 2013 93 102
#> 4 Aguascalientes 2014 94 103
#> 5 Aguascalientes 2015 95 104
#> 6 Aguascalientes 2016 96 105
#> 7 Aguascalientes 2017 97 106
#> 8 Aguascalientes 2018 98 107
#> 9 Aguascalientes 2019 99 108
#> 10 Aguascalientes 2020 100 109
#> 11 Jalisco 2011 91 100
#> 12 Jalisco 2012 92 101
#> 13 Jalisco 2013 93 102
#> 14 Jalisco 2014 94 103
#> 15 Jalisco 2015 95 104
#> 16 Jalisco 2016 96 105
#> 17 Jalisco 2017 97 106
#> 18 Jalisco 2018 98 107
#> 19 Jalisco 2019 99 108
#> 20 Jalisco 2020 100 109
data %>%
group_by(state) %>%
mutate(
across(c(gdp, population), ~(.[year == 2020] - .) / ., .names = '{col}_%change')
)
#> # A tibble: 20 x 6
#> # Groups: state [2]
#> state year population gdp `gdp_%change` `population_%change`
#> <chr> <int> <int> <int> <dbl> <dbl>
#> 1 Aguascalientes 2011 91 100 0.09 0.0989
#> 2 Aguascalientes 2012 92 101 0.0792 0.0870
#> 3 Aguascalientes 2013 93 102 0.0686 0.0753
#> 4 Aguascalientes 2014 94 103 0.0583 0.0638
#> 5 Aguascalientes 2015 95 104 0.0481 0.0526
#> 6 Aguascalientes 2016 96 105 0.0381 0.0417
#> 7 Aguascalientes 2017 97 106 0.0283 0.0309
#> 8 Aguascalientes 2018 98 107 0.0187 0.0204
#> 9 Aguascalientes 2019 99 108 0.00926 0.0101
#> 10 Aguascalientes 2020 100 109 0 0
#> 11 Jalisco 2011 91 100 0.09 0.0989
#> 12 Jalisco 2012 92 101 0.0792 0.0870
#> 13 Jalisco 2013 93 102 0.0686 0.0753
#> 14 Jalisco 2014 94 103 0.0583 0.0638
#> 15 Jalisco 2015 95 104 0.0481 0.0526
#> 16 Jalisco 2016 96 105 0.0381 0.0417
#> 17 Jalisco 2017 97 106 0.0283 0.0309
#> 18 Jalisco 2018 98 107 0.0187 0.0204
#> 19 Jalisco 2019 99 108 0.00926 0.0101
#> 20 Jalisco 2020 100 109 0 0
Created on 2022-03-28 by the reprex package (v2.0.1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Johan Rosa |
