【发布时间】:2015-10-27 01:40:14
【问题描述】:
我正在使用与提取相对应的数据集:
set.seed(1)
df <- data.frame(indicator=runif(n = 100),cohort=letters[1:4],
year=rep(1976:2000, each=4))
我想为数据集中表示的每个cohort 生成一个具有同比百分比变化的变量。我尝试使用下面的代码(from this discussion):
df$ind_per_chng <- transform(new.col=c(NA,indicator[-1]/indicator[-nrow(df)]-1))
但我有兴趣让它在每个子组中工作并只生成一个具有百分比变化的额外列,而不是当前创建的一组列:
> 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
编辑
回答有用的cmets,输出的格式应该对应下表:
原始data.frame 没有其他变化,除了为每个群组的选定变量提供不同年份的百分比变化值的列。
【问题讨论】:
标签: r dataframe time-series transform