在一对数据行中执行差异

时间:2016-06-01 14:46:21

标签: r

我的数据框是:

df:

one     two     three
a       8       x
a       12      y
b       9       x
b       3       y

结果应该是:

one     two
a       4
b       6
你可以帮帮我..

3 个答案:

答案 0 :(得分:1)

以下是使用aggregate的基本R方法:

aggregate(two~one, data=df, FUN=function(i) abs(diff(i)))

数据

df <- read.table(header=T, text="one     two     three
a       8       x
                 a       12      y
                 b       9       x
                 b       3       y")

答案 1 :(得分:1)

以下是使用dplyr

执行此操作的另一种方法
library(dplyr)

 df <- data.frame(one = factor(c("a", "a", "b", "b")),
                 two = c(8,12,9,3),
                 three = factor(c("x", "y", "x", "y")))

 answer <- df %>% group_by(one) %>% summarise(two = abs(diff(two)))

 > answer
Source: local data frame [2 x 2]

     one   two
   (fctr) (dbl)
 1      a     4
 2      b     6

答案 2 :(得分:0)

您可以尝试:

library(data.table)
setDT(df)[, .(two = abs(diff(two))), .(one)]

使用plyr包:

library(plyr)
ddply(df, 'one', summarise, two = abs(diff(two)))
  one two
1   a   4
2   b   6