使用dplyr计算数据帧中的行之间的差异? [英] Calculating the difference between rows in a dataframe using dplyr?

查看:107
本文介绍了使用dplyr计算数据帧中的行之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据帧的ids和时间戳。我想计算一个单独ID的每个连续时间戳之间的差异。



我的数据框如下所示:

  id time 
Alpha 1
Alpha 4
Alpha 7
Beta 5
Beta 10

我正在尝试添加如 time.difference

  id时间time.difference 
Alpha 1 NA
Alpha 4 3
Alpha 7 4
Beta 5 NA
Beta 10 5

是否有一个干净的方式这使用dplyr? (或tidyr或其他比vanilla R更容易阅​​读的东西)

解决方案

像这样:

  dat%>%
group_by(id)%>%
mutate(time.difference = time-lag )


I have a dataframe of ids and timestamps. I'd like to calculate the difference between each sequential timestamp for an individual id.

My dataframe looks like this:

id  time
Alpha   1
Alpha   4
Alpha   7
Beta    5
Beta    10

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

Is there a clean way to do this using dplyr? (or tidyr or something else that's easier to read than vanilla R?)

解决方案

Like this:

dat %>% 
  group_by(id) %>% 
  mutate(time.difference = time - lag(time))

这篇关于使用dplyr计算数据帧中的行之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆