2017-02-24 117 views
0

我有一個表結構如下:Year,Month,ValueA,ValueB,ValueC等。我想根據年份和月份對錶格進行分組,但是根據列值的差異進行聚合。Group By Row Value Difference

Year Month ValueA ValueB ValueC 
2016 1  40  53  49 
2017 2  29  31  26 
2016 1  25  20  31 
2017 2  22  30  29 

我要輸出的表看起來像:

Year Month ValueA ValueB ValueC 
2016 1  15  33  18 
2017 2  7  1  3 

我怎麼會去嗎?任何幫助深表感謝。

+0

的可能的複製http://stackoverflow.com/questions/14846547/calculating-difference-row-values-by-group-在-R – akrun

回答

4

我們可以使用基礎R aggregate和組由YearMonth計算兩行之間的差異。

abs(aggregate(.~Year + Month, df, diff)) 

# Year Month ValueA ValueB ValueC 
#1 2016  1  15  33  18 
#2 2017  2  7  1  3 
2

下面是使用dplyr包的方式:

library(tidyverse) 
df <- data.frame(Year = c(2016, 2017, 2016, 2017), 
      Month = c(1, 2, 1, 2), 
      ValueA = c(40, 29, 25, 22), 
      ValueB = c(53, 31, 20, 30), 
      ValueC = c(49, 26, 31, 29)) 

df1 <- df %>% 
    group_by(Year, Month) %>% 
    summarize(ValueA = abs(diff(ValueA)), ValueB = abs(diff(ValueB)), ValueC = abs(diff(ValueC))) 
1

可以使用plyr使用this thread描述的方法:

ddply(df, .(Year, Month), numcolwise(diff))