gpt4 book ai didi

r - R 中的时差

转载 作者:行者123 更新时间:2023-12-01 12:46:29 25 4
gpt4 key购买 nike

我有一些看起来像这样的数据:

id    time
1 2013-02-04 02:20:59
1 2013-02-04 02:21:05
1 2013-02-04 02:21:24
2 2013-02-04 02:21:26
2 2013-02-04 02:22:19
2 2013-02-04 02:22:35

我想计算两个时间值之间每个 id 的时间差,例如:

id 1 02:21:05-02:20:59=00:00:06. 

我如何在 R 中执行此操作?

最佳答案

你应该按时做 diff 以及 id 然后使用 ifelse 填充第三列

df <- structure(list(id = c(1L, 1L, 1L, 2L, 2L, 2L), 
time = structure(c(1359915659, 1359915665, 1359915684,
1359915686, 1359915739, 1359915755), class = c("POSIXct",
"POSIXt"), tzone = "")), .Names = c("id", "time"), row.names = c(NA, -6L),
class = "data.frame")
df
## id time
## 1 1 2013-02-04 02:20:59
## 2 1 2013-02-04 02:21:05
## 3 1 2013-02-04 02:21:24
## 4 2 2013-02-04 02:21:26
## 5 2 2013-02-04 02:22:19
## 6 2 2013-02-04 02:22:35

## here you are checking if that result is diff in time only when diff in id is 0
df$result <- c(0, ifelse(diff(df$id) == 0, diff(df$time), 0))

df
## id time result
## 1 1 2013-02-04 02:20:59 0
## 2 1 2013-02-04 02:21:05 6
## 3 1 2013-02-04 02:21:24 19
## 4 2 2013-02-04 02:21:26 0
## 5 2 2013-02-04 02:22:19 53
## 6 2 2013-02-04 02:22:35 16

关于r - R 中的时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15353731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com