使用dplyr按组计算连续行之间的差异? [英] Calculating the difference between consecutive rows by group using dplyr?
本文介绍了使用dplyr按组计算连续行之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个ID和时间戳的数据框。我想计算单个ID的每个连续时间戳之间的差。
I have a dataframe of ids and timestamps. I'd like to calculate the difference between each sequential timestamp for an individual id.
我的数据框如下所示:
id time
Alpha 1
Alpha 4
Alpha 7
Beta 5
Beta 10
我正尝试在下面添加类似 time.difference
的列:
I'm trying to add a column like time.difference
below:
id time time.difference
Alpha 1 NA
Alpha 4 3
Alpha 7 4
Beta 5 NA
Beta 10 5
有没有一种清洁的方法这使用dplyr? (或tidyr或比香草R更容易阅读的东西?)
Is there a clean way to do this using dplyr? (or tidyr or something else that's easier to read than vanilla R?)
推荐答案
就像这样:
dat %>%
group_by(id) %>%
mutate(time.difference = time - lag(time))
这篇关于使用dplyr按组计算连续行之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文