如何更简洁地从“开始 - 结束”字符串计算持续时间

Chr*_*ann 4 duration r lubridate

我有时间戳指示事件开始的时间和结束的时间:

x <- "00:01:00.000 - 00:01:10.500"
Run Code Online (Sandbox Code Playgroud)

我需要计算事件的持续时间。利用hms从包lubridate以及lapplystrsplit它给我预期的输出:

library(lubridate)
unlist(lapply(strsplit(x, split=" - "), function(x) as.numeric(hms(x))))[2] - unlist(lapply(strsplit(x, split=" - "), function(x) as.numeric(hms(x))))[1] 
[1] 10.5
Run Code Online (Sandbox Code Playgroud)

但我觉得代码完全不优雅,一点也不简洁。有没有更好的方法来获得持续时间?

编辑

如果,因为事实确实如此,有很多超过在短短的一个值x,如:

x <- c("00:01:00.000 - 00:01:10.500", "00:12:12.000 - 00:13:10.500")
Run Code Online (Sandbox Code Playgroud)

我想出了这个解决方案:

timepoints <- lapply(strsplit(x, split=" - "), function(x) as.numeric(hms(x)))
duration <- lapply(timepoints, function(x) x[2]-x[1])

duration
[[1]]
[1] 10.5

[[2]]
[1] 58.5
Run Code Online (Sandbox Code Playgroud)

但是,再一次,肯定有一个更好、更短的。

Ron*_*hah 6

这是一种方法:

as.numeric(diff(lubridate::hms(strsplit(x, split=" - ")[[1]])))
#[1] 10.5
Run Code Online (Sandbox Code Playgroud)

将其保留在基数 R 中:

as.numeric(diff(as.POSIXct(strsplit(x, split=" - ")[[1]], format = '%H:%M:%OS')))
#[1] 10.5
Run Code Online (Sandbox Code Playgroud)

对于多个值,我们可以使用sapply

library(lubridate)
sapply(strsplit(x, " - "), function(y) diff(period_to_seconds(hms(y))))

#[1] 10.5 80.5
Run Code Online (Sandbox Code Playgroud)

并在基础 R 中:

sapply(strsplit(x, " - "), function(y) {
   x1 <- as.POSIXct(y, format = '%H:%M:%OS')
   difftime(x1[2], x1[1], units = "secs")
})
Run Code Online (Sandbox Code Playgroud)