R 使用几种不同的格式分析经过的时间/时间跨度/持续时间

R 使用几种不同的格式分析经过的时间/时间跨度/持续时间,r,datetime,R,Datetime,我需要用几种不同的格式分析时间跨度,包括天、小时、分钟、秒.ms,用::%OS,%H:%OS,%H:%m:%OS或%d:%H:%m:%OS。例如: x <- c("28.6575", "1:14.0920", "1:5:38.1230", "5:23:59:38.7211") 另一种方法是将格式化值转换为秒(例如,1:14.0920~~~>74.0920秒)。但是,我无法找到一种方便的方法来使用R来完成此操作。您还可以添加缺少的小时、分钟和天数据 例如,如果v1是你的向量,你可以: r

我需要用几种不同的格式分析时间跨度,包括天、小时、分钟、秒.ms,用
%OS
%H:%OS
%H:%m:%OS
%d:%H:%m:%OS
。例如:

x <- c("28.6575", "1:14.0920", "1:5:38.1230", "5:23:59:38.7211") 

另一种方法是将格式化值转换为秒(例如,
1:14.0920~~~>74.0920秒
)。但是,我无法找到一种方便的方法来使用R来完成此操作。

您还可以添加缺少的小时、分钟和天数据

例如,如果
v1
是你的向量,你可以:

res<-sapply(v1,function(x){
        if(str_count(x ,":")==2) paste0("1:",x)
        else if(str_count(x, ":") < 2)  paste0("1:",paste(rep("0:",2-str_count(x ,":")),collapse=""),x)
        else as.character(x)
        })
strptime(res, "%d:%H:%M:%OS")

res这里是@Konrad Rudolph评论的扩展版本:

# split time spans into their different time elements
l <- strsplit(x, ":")

# pad vector with leading zeros. Here 4 is the maximum number of time elements
m <- sapply(l, function(x) as.numeric(c(rep(0, 4 - length(x)), x)))

# convert result to desired unit, e.g. seconds
m[1 , ] * 24*60*60 + m[2 , ] * 60*60 + m[3 , ] * 60 + m[4 , ]
# [1]     28.6575     74.0920   3938.1230 518378.7211
#将时间跨度划分为不同的时间元素

l我想你不会自己动手解析字符串,例如使用正则表达式(或者,在这个简单的例子中,通过组合
strsplit
as.numeric
),然后从中构造一个时间跨度。顺便说一句,时间跨度不是日期/时间,而是两个日期/时间之间的差异。有一些微妙之处使他们与众不同。
# split time spans into their different time elements
l <- strsplit(x, ":")

# pad vector with leading zeros. Here 4 is the maximum number of time elements
m <- sapply(l, function(x) as.numeric(c(rep(0, 4 - length(x)), x)))

# convert result to desired unit, e.g. seconds
m[1 , ] * 24*60*60 + m[2 , ] * 60*60 + m[3 , ] * 60 + m[4 , ]
# [1]     28.6575     74.0920   3938.1230 518378.7211