在小标题上逐组减去值

时间:2018-09-19 14:08:21

标签: r dplyr tibble

我有一个简单的小标题,想将它们分组后计算出值的绝对差:

tibb <- tibble(id = c("A", "B", "C","A", "B", "C"), value = c(5,4,3,7,8,9))

# A tibble: 6 x 2
  id    value
  <chr> <dbl>
1 A         5
2 B         4
3 C         3
4 A         7
5 B         8
6 C         9

tibb %>% group_by(id) %>% summarize(diff = function(x,y){abs(x-y)})

dplyr返回一个错误,指出不支持diff。

输出应如下所示:

# A tibble: 3 x 2
  id      sum
  <chr> <int>
1 A         2
2 B         4
3 C         6

Error in summarise_impl(.data, dots) : 
  Column `diff` is of unsupported type function

有什么方法可以计算出来吗?

1 个答案:

答案 0 :(得分:0)

如果每个组中都有2个值,请尝试以下操作:

tibb <- tibble(id = c("A", "B", "C","A", "B", "C"), value = c(5,4,3,7,8,9))
tibb

tibb %>% group_by(id) %>% summarize(diff = abs(diff(value)))
#or
tibb %>% group_by(id) %>% summarize(diff = abs(value[1] - value[2]))