计算一列中从第一年到去年的百分比变化

Tde*_*eus 3 r percentage dplyr

我想计算第一年2015和最后一年之间的百分比变化,2017作为每个city.

这是我的可重现示例,其中最后一列perct_change_2015_2017是所需的输出。我如何在 R 中为一大堆城市做到这一点?最好在 dplyr 中。

使用正确的百分比变化数字进行编辑

example <- structure(list(city = c("Amsterdam", "Amsterdam", "Amsterdam", 
"Rotterdam", "Rotterdam", "Rotterdam"), year = c(2015L, 2016L, 
2017L, 2015L, 2016L, 2017L), value = c(30L, 35L, 46L, 23L, 19L, 
17L), perct_change_2015_2017 = c(0.5333333333, 0.5333333333, 
0.5333333333, -0.2608695652, -0.2608695652, -0.2608695652)), .Names = c("city", 
"year", "value", "perct_change_2015_2017"), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"), spec = structure(list(
    cols = structure(list(city = structure(list(), class = c("collector_character", 
    "collector")), year = structure(list(), class = c("collector_integer", 
    "collector")), value = structure(list(), class = c("collector_integer", 
    "collector")), perct_change_2015_2017 = structure(list(), class = c("collector_double", 
    "collector"))), .Names = c("city", "year", "value", "perct_change_2015_2017"
    )), default = structure(list(), class = c("collector_guess", 
    "collector"))), .Names = c("cols", "default"), class = "col_spec"))

example

 A tibble: 6 x 4
  city       year value perct_change_2015_2017
  <chr>     <int> <int>                  <dbl>
1 Amsterdam  2015    30                  0.533
2 Amsterdam  2016    35                  0.533
3 Amsterdam  2017    46                  0.533
4 Rotterdam  2015    23                 -0.260
5 Rotterdam  2016    19                 -0.260
6 Rotterdam  2017    17                 -0.260
Run Code Online (Sandbox Code Playgroud)

Gre*_*gor 5

无论存在多少年,此方法将始终使用20152017。我更喜欢使用 www 的解决方案firstlast一般,但如果你有更多的年份并想要这些特定的年份,这里是如何做到的。

example %>% group_by(city) %>%
  mutate(perct_change_2015_2017 =
    (value[year == 2017] - value[year == 2015]) / value[year == 2015]
  )
# # A tibble: 6 x 4
# # Groups:   city [2]
#        city  year value perct_change_2015_2017
#       <chr> <int> <int>                  <dbl>
# 1 Amsterdam  2015    30              0.5333333
# 2 Amsterdam  2016    35              0.5333333
# 3 Amsterdam  2017    46              0.5333333
# 4 Rotterdam  2015    23             -0.2608696
# 5 Rotterdam  2016    19             -0.2608696
# 6 Rotterdam  2017    17             -0.2608696
Run Code Online (Sandbox Code Playgroud)