我的数据框是:
df:
one two three
a 8 x
a 12 y
b 9 x
b 3 y
结果应该是:
one two
a 4
b 6
你可以帮帮我..
答案 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