每个子组的备用行的差异相同

时间:2017-06-08 21:03:44

标签: r dplyr row difference alternate

我有数据框,我需要找到差异但是对于每个替代行,差异应保持相同,因为要做的事情是这样的:

enter image description here

但我用过这个:

things <- data.frame( category = c("A","B","A","B","A","B","A","B","A","B"),
                      things2do = c("ball","ball","bat","bat","hockey","hockey","volley ball","volley ball","foos ball","foos ball"),
                      number = c(12,5,4,1,0,2,2,0,0,2))


    things %>% 
      mutate(diff = number - lead(number,order_by=things2do))

但是没有用,因为我得到了这个: enter image description here

我能在这里得到一些帮助吗?

2 个答案:

答案 0 :(得分:1)

library(tidyverse)

things2 <- things %>%
  spread(category, number) %>%
  mutate(diff = B - A) %>%
  gather(category, number, A:B) %>%
  select(category, things2do, number, diff) %>%
  arrange(things2do)

答案 1 :(得分:1)

一种方法是按things2do对数据进行分组,然后进行迭代差异。

library(dplyr)
things %>% 
  group_by(things2do) %>%
  mutate(diff = diff(number))