相对于每组中的值进行缩放(通过dplyr)

sha*_*roz 8 r dplyr

我有一组时间序列,我想在特定的时间间隔内相对于它们的值来缩放每个时间序列.这样,每个系列在那个时候都是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]]
}
Run Code Online (Sandbox Code Playgroud)

编辑:修改了问题,使基准时间点不可索引.有时"时间"列实际上是一个因素,不一定是序数.

Hug*_*ugh 8

first在dplyr中使用,确保您使用order_by

data %>% 
  group_by(category) %>% 
  mutate(value = value / first(value, order_by = year))
Run Code Online (Sandbox Code Playgroud)


osh*_*hun 8

这个解决方案与@thelatemail非常相似,但我认为它足够不同,值得自己回答,因为它根据条件选择索引:

data %>%
    group_by(category) %>%
    mutate(value = value/value[year == baseYear])

#   category  year      value
#...     ...   ...       ...
#7         A  2002 1.00000000
#8         B  2002 1.00000000
#9         C  2002 1.00000000
#10        A  2003 0.86462789
#11        B  2003 1.07217943
#12        C  2003 0.82209897
Run Code Online (Sandbox Code Playgroud)

(数据输出已被截断.要set.seed(123)在创建时复制这些结果data.)