[英]Time difference between two time stamps
I have a dataframe that contains the following datetime stamps of the class "POSIXct" "POSIXt"
: 我有一个包含以下类别
"POSIXct" "POSIXt"
日期时间戳的数据"POSIXct" "POSIXt"
:
1899-12-30 08:00:37
1899-12-30 08:03:54
1899-12-30 08:05:31
1899-12-30 08:12:55
I need to calculate the difference (in minutes) between subsequent rows. 我需要计算后续行之间的差异(以分钟为单位)。 The result for the first row should be (ie 08:03:54-08:00:37):
第一行的结果应为(即08:03:54-08:00:37):
1899-12-30 08:00:37 3.28
I use this code to calculate the difference, but the outputs do not coincide with manual calculations. 我使用此代码来计算差异,但是输出与手动计算不一致。
c_time <- df$datetime
intervals = c(difftime(ymd_hms(c_time[2:length(c_time)]),
ymd_hms(c_time[1:(length(c_time)-1)]),
units="mins"),0)
You could use lubridate
and dplyr
. 您可以使用
lubridate
和dplyr
。 It is one option among others. 这是其他选择之一。
df <- data.frame(dtime = c(
"1899-12-30 08:00:37",
"1899-12-30 08:03:54",
"1899-12-30 08:05:31",
"1899-12-30 08:12:55"))
library(dplyr)
library(lubridate)
df %>%
mutate(dtime = ymd_hms(dtime),
diff = lead(dtime) - dtime)
#> dtime diff
#> 1 1899-12-30 08:00:37 3.283333 mins
#> 2 1899-12-30 08:03:54 1.616667 mins
#> 3 1899-12-30 08:05:31 7.400000 mins
#> 4 1899-12-30 08:12:55 NA mins
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.