chron times 类将持续时间表示为天数和一天的分数。我们定义了两个函数来从我们的自定义文本格式转换为times 和从times 转换为我们的自定义文本格式。
library(chron)
text2times <- function(x) with(read.table(text = as.character(x), sep = "d", as.is = TRUE),
V1 + times(V2))
times2text <- function(x) paste(as.integer(x), format(x %% 1), sep = "d")
dd <- transform(d, diffdays = text2times(stop) - text2times(start),
difftext = times2text(text2times(stop) - text2times(start)))
给予:
start stop diffdays difftext
1 1d02:03:04 2d02:03:50 1.000532 1d00:00:46
S3 自定义类 dur
这对于您的需要可能有点过头了,但我们可以定义一个 S3 类 dur 来执行此操作。
as.dur <- function(x, ...) UseMethod("as.dur")
as.dur.character <- function(x, ...) structure(text2times(x), class = c("dur", "times"))
as.dur.factor <- function(x, ...) as.dur(as.character(x))
format.dur <- function(x, ...) times2text(times(x))
# new it's easy
transform(d, diff = as.dur(stop) - as.dur(start))
给予:
start stop diff
1 1d02:03:04 2d02:03:50 1d00:00:46
在 read.table 中使用 dur
我们也可以将数据直接读入dur类
setAs("character", "dur", function(from) as.dur(from))
# test input - normally read from file but to keep answer self contained use string
Lines <- "start stop
1d02:03:04 2d02:03:50"
# now it's even easier
dd <- read.table(text = Lines, header = TRUE, colClasses = c("dur", "dur"))
transform(dd, diff = stop - start)
## start stop diff
## 1 1d02:03:04 2d02:03:50 1d00:00:46
注意
可重现形式的样本输入:
d <- data.frame(start = "1d02:03:04", stop = "2d02:03:50")