在 tibble 上按组减去值

subtracting values group wise on a 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 return 不支持 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

有什么方法可以计算吗?

如果每组中有 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]))