【发布时间】:2014-11-25 01:42:50
【问题描述】:
我有一组时间序列,我想在特定间隔内相对于它们的值对它们中的每一个进行缩放。这样一来,每个系列在那时都会处于 1.0 并按比例变化。
我不知道如何用 dplyr 做到这一点。
这是一个使用 for 循环的工作示例:
library(dplyr)
data = expand.grid(
category = LETTERS[1:3],
year = 2000:2005)
data$value = runif(nrow(data))
# the first time point in the series
baseYear = 2002
# for each category, divide all the values by the category's value in the base year
for(category in as.character(levels(factor(data$category)))) {
data[data$category == category,]$value = data[data$category == category,]$value / data[data$category == category & data$year == baseYear,]$value[[1]]
}
编辑:修改了问题,使基准时间点不可索引。有时“时间”列实际上是一个因素,不一定是序数。
【问题讨论】: