我有数据框,我需要找到差异但是对于每个替代行,差异应保持相同,因为要做的事情是这样的:
但我用过这个:
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))
我能在这里得到一些帮助吗?
答案 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))