计算不同时间段内子组的数据框中的百分比变化

问题描述 投票:0回答:1

有一些类似的问题,但我没有遇到一个有助于我的具体情况;每个季度都会记录每个事件名称的事件计数,每个事件都会进行多次传递以捕获缺失的计数。我想比较每次通过的计数百分比变化与他们各自通过的先前计数数。

这是我目前拥有的数据(不同的值,但格式相同):

ID <- c(221, 221, 345, 345, 209, 209, 209, 19, 19, 19, 536, 536, 536)
Pass <- c(1, 2, 1, 2, 1, 2, 3, 1, 2, 3, 1, 2, 3)
Event_count <- c(2000, 100, 2050, 150, 50000, 10000, 600, 51000, 11000, 700, 50500, 10500, 650)
Event_name <- c(rep('filter', 4) , rep('observations', 9))
Date <- c(rep('2015-03-01',2) , rep('2015-06-01',2) , rep('2015-03-01',3) , rep('2015-06-01',3), rep('2015-09-01',3))  
df <- data.frame(ID, Pass, Event_count, Event_name, Date)

    ID Pass Event_count   Event_name       Date
1  221    1        2000       filter 2015-03-01
2  221    2         100       filter 2015-03-01
3  345    1        2050       filter 2015-06-01
4  345    2         150       filter 2015-06-01
5  209    1       50000 observations 2015-03-01
6  209    2       10000 observations 2015-03-01
7  209    3         600 observations 2015-03-01
8   19    1       51000 observations 2015-06-01
9   19    2       11000 observations 2015-06-01
10  19    3         700 observations 2015-06-01
11 536    1       50500 observations 2015-09-01
12 536    2       10500 observations 2015-09-01
13 536    3         650 observations 2015-09-01

这是我想要的输出(如果您能想出更好的方式来显示这些数据,请告诉我!)

Percentage_change <- c(NA, NA, 2.5, 50, NA, NA, NA, 2, 10, 16.67, -0.98, -4.55, -7.14)
df2 <- data.frame(ID, Pass, Event_count, Event_name, Date,Percentage_change)

    ID Pass Event_count   Event_name       Date Percentage_change
1  221    1        2000       filter 2015-03-01                NA
2  221    2         100       filter 2015-03-01                NA
3  345    1        2050       filter 2015-06-01              2.50
4  345    2         150       filter 2015-06-01             50.00
5  209    1       50000 observations 2015-03-01                NA
6  209    2       10000 observations 2015-03-01                NA
7  209    3         600 observations 2015-03-01                NA
8   19    1       51000 observations 2015-06-01              2.00
9   19    2       11000 observations 2015-06-01             10.00
10  19    3         700 observations 2015-06-01             16.67
11 536    1       50500 observations 2015-09-01             -0.98
12 536    2       10500 observations 2015-09-01             -4.55
13 536    3         650 observations 2015-09-01             -7.14

我只有相对基本的R知识,所以我不知道是否有任何软件包可以帮助我 - 任何帮助/解释,你可以提供给我将不胜感激。

r dataframe time-series percentage
1个回答
1
投票

这似乎返回了您想要的值

library(dplyr)
df %>% 
  group_by(Event_name, Pass) %>% 
  mutate(Percentage_change=(Event_count/lag(Event_count)-1)*100)
© www.soinside.com 2019 - 2024. All rights reserved.