【问题标题】:How to calculate percentage change within a partition? - R如何计算分区内的百分比变化? -R
【发布时间】:2016-02-22 10:17:44
【问题描述】:

我有一系列性能指标,想计算上一行但在定义的分区内的百分比变化,如下所示:

   index metric percent_change
   A     10     0.0
   A     20     1.0
   A     10     -.50
   A     5      -.50
   B     10     0
   B     5      -.50
   B     10     1.00

如何在 R 中完成此操作?

【问题讨论】:

  • 还有with(df1, ave(metric, index, FUN = function(x) c(0, (tail(x, -1) - head(x, -1)) / head(x, -1))))

标签: r partition calculated-field


【解决方案1】:

我们可以使用data.table。将'data.frame'转换为'data.table'(setDT(df1)),按'index'分组,我们从'fill'的滞后中减去'fill'并除以它并分配(:=)结果创建'percent_change'。

library(data.table)#v1.9.6+
setDT(df1)[, percent_change := {tmp <- shift(metric, fill=metric[1L])
                 (metric-tmp)/tmp} , by =  index]
df1
#   index metric percent_change
#1:     A     10            0.0
#2:     A     20            1.0
#3:     A     10           -0.5
#4:     A      5           -0.5
#5:     B     10            0.0
#6:     B      5           -0.5
#7:     B     10            1.0

或使用dplyr

library(dplyr)
df1 %>%
     group_by(index) %>%
     mutate(percent_change = (metric- lag(metric, default=metric[1L]))/lag(metric, default=metric[1L]))

数据

df1 <- structure(list(index = c("A", "A", "A", "A", "B", "B", "B"), 
metric = c(10L, 20L, 10L, 5L, 10L, 5L, 10L)), .Names = c("index", 
"metric"), 
 row.names = c(NA, -7L), class = "data.frame")

【讨论】:

    【解决方案2】:

    使用基础包的另一种选择:

    df1$percent_change <- unlist(
    tapply(df1$metric, df1$index, function(x) c(0, x[-1]/x[1]-1) )
    )
    

    或者和rawr提出的很相似

    df1$percent_change <- ave(df1$metric, df1$index, FUN=function(x) c(0,x[-1]/x[1]-1))
    

    输出:

      index metric percent_change
    1     A     10            0.0
    2     A     20            1.0
    3     A     10            0.0
    4     A      5           -0.5
    5     B     10            0.0
    6     B      5           -0.5
    7     B     10            0.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 2018-06-20
      • 2013-01-14
      相关资源
      最近更新 更多