繁体   English   中英

如何从数据框中找到两个日期/时间列之间的时间差

[英]How to find the difference in time between two date/time columns from a data frame

我有一个如下数据框,

S.no          f_req_time         f_drop_time
1    2016-07-11 06:04:00   2016-07-11 06:44:00
2    2016-07-11 12:20:00   2016-07-11 13:10:00
3    2016-07-11 16:19:00   2016-07-11 17:25:00
4    2016-07-12 09:03:00   2016-07-12 09:58:00
5    2016-07-12 12:10:00   2016-07-12 12:49:00

我想添加一列称为等待时间,这将是列“ f_drop_time”(2016-07-11 06:44:00)的第一个值(即S.no.1的第一个值和第二个值,即'f_req_time'的S.no.2(2016-07-11 12:20:00)。如何创建所有时间差的列。我尝试了for循环。它返回所有null。

日期时间列为POSIXct格式

我的代码,

funtion<-for (i in 1:nrow(driver_27)) {
  driver_27$wait <- driver_27$f_drop_time[i+1]-driver_27$f_req_time[i]
}

我们可以采取lead的第一列,并使用difftime做减法(请注意,目前尚不清楚有关unit

driver_27$wait <- with(driver_27, as.numeric(difftime(c(f_req_time[-1], NA),
                     f_drop_time, unit = 'hour')))
driver_27$wait
#[1]  5.60000  3.15000 15.63333  2.20000       NA

数据

driver_27 <- structure(list(S.no = 1:5, f_req_time = structure(c(1468231440, 
1468254000, 1468268340, 1468328580, 1468339800), class = c("POSIXct", 
"POSIXt"), tzone = ""), f_drop_time = structure(c(1468233840, 
1468257000, 1468272300, 1468331880, 1468342140), class = c("POSIXct", 
"POSIXt"), tzone = "")), .Names = c("S.no", "f_req_time", "f_drop_time"
), row.names = c(NA, -5L), class = "data.frame")

此解决方案抵消了f_drop_time并存储在新列中,以方便验证/检查。 它还使用lubridate::interval()来计算等待时间,以小时为单位:

# data
data.frame(
  f_req_time = c("2016-07-11 06:04:00" , "2016-07-11 12:20:00", "2016-07-11 16:19:00", "2016-07-12 09:03:00", "2016-07-12 12:10:00"),
  f_drop_time = c("2016-07-11 06:44:00", "2016-07-11 13:10:00", "2016-07-11 17:25:00", "2016-07-12 09:58:00", "2016-07-12 12:49:00"),
  stringsAsFactors = FALSE
) -> x

# create a new column that has ofset f_drop_time by 1
x %>% mutate(temp = c(f_drop_time[-1], NA)) -> x

# convert to lubridate format
ymd_hms(x$temp) -> x$temp
ymd_hms(x$f_drop_time) -> x$f_drop_time

# calculates the interval in hours in 'wait_time' column
(x %>% mutate(wait_time = interval(f_drop_time, temp)/hours(1)) -> x)

# removes temp
x[, !names(x) %in% c("temp")] -> x

产生(带有临时数据):

           f_req_time         f_drop_time                temp wait_time
1 2016-07-11 06:04:00 2016-07-11 06:44:00 2016-07-11 13:10:00  6.433333
2 2016-07-11 12:20:00 2016-07-11 13:10:00 2016-07-11 17:25:00  4.250000
3 2016-07-11 16:19:00 2016-07-11 17:25:00 2016-07-12 09:58:00 16.550000
4 2016-07-12 09:03:00 2016-07-12 09:58:00 2016-07-12 12:49:00  2.850000
5 2016-07-12 12:10:00 2016-07-12 12:49:00                <NA>        NA

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM