↓dplyrgroup_bylag
library(dplyr)
#
df <- data.frame(
year = rep(seq(2005, 2016), 2),
pref = as.factor(rep(c("", ""), each = 12)),
pop = as.integer(runif(12 * 2, 100, 200))
)
print(df)
#> year pref pop
#> 1 2005 176
#> 2 2006 149
...
#> 11 2015 110
#> 12 2016 126
#> 13 2005 109
#> 14 2006 127
...
#> 23 2015 135
#> 24 2016 125
#
df %>%
#
dplyr::group_by(pref) %>%
#
dplyr::arrange(year) %>%
# (/)
dplyr::mutate(
rate = pop/dplyr::lag(pop)
)
#> # A tibble: 24 x 4
#> # Groups: pref [2]
#> year pref pop rate
#>
#> 1 2005 176 NA
#> 2 2005 109 NA
#> 3 2006 149 0.847
#> 4 2006 127 1.17
#> 5 2007 162 1.09
#> 6 2007 155 1.22
...