每个子组的交替行的差异相同
Same difference in alternate rows per sub group
我有一个数据框,我需要在其中找到差异,但是对于每个交替行,差异应该保持不变,因为要做的事情是一样的,就像这样:
但我用过这个:
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))
但这没有帮助,因为我得到了这个:
我可以得到一些帮助吗?
library(tidyverse)
things2 <- things %>%
spread(category, number) %>%
mutate(diff = B - A) %>%
gather(category, number, A:B) %>%
select(category, things2do, number, diff) %>%
arrange(things2do)
一种方法是按 things2do
对数据进行分组,然后进行迭代差分。
library(dplyr)
things %>%
group_by(things2do) %>%
mutate(diff = diff(number))
我有一个数据框,我需要在其中找到差异,但是对于每个交替行,差异应该保持不变,因为要做的事情是一样的,就像这样:
但我用过这个:
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))
但这没有帮助,因为我得到了这个:
我可以得到一些帮助吗?
library(tidyverse)
things2 <- things %>%
spread(category, number) %>%
mutate(diff = B - A) %>%
gather(category, number, A:B) %>%
select(category, things2do, number, diff) %>%
arrange(things2do)
一种方法是按 things2do
对数据进行分组,然后进行迭代差分。
library(dplyr)
things %>%
group_by(things2do) %>%
mutate(diff = diff(number))