仅当列值在 R 中匹配时才计算 difftime
Calculate difftime only if a column value matches in R
如果列 serviceID 具有相同的值,我必须找出连续行的日期时间(以秒为单位)之间的差异。
dt :
日期时间
服务ID
2021-04-0302:53:43
2000
2021-04-0302:53:45
2000
2021-04-0302:53:47
2000
2021-04-0302:53:49
2012
2021-04-0302:53:51
2012
2021-04-0302:53:53
2015
2021-04-0302:53:55
2015
2021-04-0302:53:57
2015
输出:
日期时间
服务ID
差异
2021-04-0302:53:43
2000
不适用
2021-04-0302:53:45
2000
2
2021-04-0302:53:47
2000
2
2021-04-0302:53:49
2012
不适用
2021-04-0302:53:51
2012
2
2021-04-0302:53:53
2015
不适用
2021-04-0302:53:55
2015
2
2021-04-0302:53:57
2015
2
如何做到这一点?我试过了但是出错了:
dt<-dt %>%
group_by(serviceID) %>%
mutate(diff= as.numeric(difftime(dt$datetime, lag(dt$datetime))))
有人可以帮忙吗?谢谢
在使用 dplyr
管道时不要使用 $
。此外,明确说明 difftime
.
中的单位总是更安全
library(dplyr)
dt <- dt %>%
group_by(serviceID) %>%
mutate(diff= as.numeric(difftime(datetime, lag(datetime), units = 'secs'))) %>%
ungroup
如果您想在 data.table
-
中执行此操作
library(data.table)
setDT(dt)
dt[, diff := as.numeric(difftime(datetime, shift(datetime), units = 'secs')), serviceID]
如果列 serviceID 具有相同的值,我必须找出连续行的日期时间(以秒为单位)之间的差异。
dt :
日期时间 | 服务ID |
---|---|
2021-04-0302:53:43 | 2000 |
2021-04-0302:53:45 | 2000 |
2021-04-0302:53:47 | 2000 |
2021-04-0302:53:49 | 2012 |
2021-04-0302:53:51 | 2012 |
2021-04-0302:53:53 | 2015 |
2021-04-0302:53:55 | 2015 |
2021-04-0302:53:57 | 2015 |
输出:
日期时间 | 服务ID | 差异 |
---|---|---|
2021-04-0302:53:43 | 2000 | 不适用 |
2021-04-0302:53:45 | 2000 | 2 |
2021-04-0302:53:47 | 2000 | 2 |
2021-04-0302:53:49 | 2012 | 不适用 |
2021-04-0302:53:51 | 2012 | 2 |
2021-04-0302:53:53 | 2015 | 不适用 |
2021-04-0302:53:55 | 2015 | 2 |
2021-04-0302:53:57 | 2015 | 2 |
如何做到这一点?我试过了但是出错了:
dt<-dt %>%
group_by(serviceID) %>%
mutate(diff= as.numeric(difftime(dt$datetime, lag(dt$datetime))))
有人可以帮忙吗?谢谢
在使用 dplyr
管道时不要使用 $
。此外,明确说明 difftime
.
library(dplyr)
dt <- dt %>%
group_by(serviceID) %>%
mutate(diff= as.numeric(difftime(datetime, lag(datetime), units = 'secs'))) %>%
ungroup
如果您想在 data.table
-
library(data.table)
setDT(dt)
dt[, diff := as.numeric(difftime(datetime, shift(datetime), units = 'secs')), serviceID]