按组别获得同比变化百分比

Kon*_*rad 3 r transform time-series dataframe

我正在使用与提取相对应的数据集:

set.seed(1)
df <- data.frame(indicator=runif(n = 100),cohort=letters[1:4],
                 year=rep(1976:2000, each=4))
Run Code Online (Sandbox Code Playgroud)

我想为数据集中表示的每个变量生成一个变量百分比同比变化cohort.我试图使用下面的代码(来自此讨论):

df$ind_per_chng <- transform(new.col=c(NA,indicator[-1]/indicator[-nrow(df)]-1))
Run Code Online (Sandbox Code Playgroud)

但是我有兴趣让它在每个子组中工作,并且只生成一个额外的列,其中包含百分比更改而不是当前创建的列集:

> head(df)
  indicator cohort year ind_per_chng.indicator ind_per_chng.cohort ind_per_chng.year
1 0.2655087      a 1976              0.2655087                   a              1976
2 0.3721239      b 1976              0.3721239                   b              1976
3 0.5728534      c 1976              0.5728534                   c              1976
4 0.9082078      d 1976              0.9082078                   d              1976
5 0.2016819      a 1977              0.2016819                   a              1977
6 0.8983897      b 1977              0.8983897                   b              1977
  ind_per_chng.new.col
1                   NA
2            0.4015509
3            0.5394157
4            0.5854106
5           -0.7779342
6            3.4544877
Run Code Online (Sandbox Code Playgroud)

编辑

要回答有用的注释,输出的格式应对应于下表:

期望的格式

data.frame除了为每个队列中所选变量的百分比变化提供值的列之外,原始组件没有其他更改.

ulf*_*der 7

我不确定我是否正确理解了你希望输出看起来像什么,但是你正在追求的是什么?

library(dplyr)
df2 <- df%>%
    group_by(cohort) %>%
    arrange(year) %>%
    mutate(pct.chg = (indicator - lag(indicator))/lag(indicator))
Run Code Online (Sandbox Code Playgroud)

如果您希望百分比为0-100而不是0-1,则添加100 * ()到最后一行,所以mutate(pct.chg = 100 * ((indicator - lag(indicator))/lag(indicator))).结果如下:

  indicator cohort year    pct.chg
1 0.2655087      a 1976         NA
2 0.2016819      a 1977 -24.039416
3 0.6291140      a 1978 211.933767
4 0.6870228      a 1979   9.204818
5 0.7176185      a 1980   4.453369
6 0.9347052      a 1981  30.250993
Run Code Online (Sandbox Code Playgroud)