我正在寻找R函数的所有帮助,它将把时间跨度,例如"15分钟"或"1小时"或"6秒"或"1天"转换为日期时间对象,如"00:15:00"或"01: 00:00"或"00:00:06"或"1960-01-02 00:00:00"(对此不确定).我确信这样的函数存在,或者有一种简洁的方法可以避免编程...
更具体地说,我想做这样的事情(使用组合函数名称transform.span.to.time):
library(chron)
times(transform.span.to.time("15 min"))
Run Code Online (Sandbox Code Playgroud)
这应该产生相同的结果
times("00:15:00")
Run Code Online (Sandbox Code Playgroud)
像transform.span.to.time("15分钟")之类的函数是否存在返回类似"00:15:00"的函数,或者是否存在如何做到这一点的技巧?
我们将假设一个空格分隔数字和单位,并且在"secs"单位之后也没有尾随空格.这将处理混合单位:
test <- "0 hours 15 min 0 secs"
transform.span <- function(test){
testh <- if(!grepl( " hour | hours ", "0 hours 15 min 0 secs")){
# First consequent if no hours
sub("^", "0:", test)} else {
sub(" hour | hours ", ":", test)}
testm <- if(!grepl( " min | minutes ", testh)) {
# first consequent if no minutes
sub(" min | minutes ", "0:", testh)} else{
sub(" min | minutes ", ":", testh) }
test.s <- if(!grepl( " sec| secs| seconds", testm)) {
# first consequent if no seconds
sub(" sec| secs| seconds", "0", testm)} else{
sub(" sec| secs| seconds", "", testm)}
return(times(test.s)) }
### Use
> transform.span(test)
[1] 00:15:00
> test2 <- "21 hours 15 min 38 secs"
> transform.span(test2)
[1] 21:15:38
Run Code Online (Sandbox Code Playgroud)
基函数?cut.POSIXt对 的一组指定值执行此操作breaks:
breaks: a vector of cut points _or_ number giving the number of\n intervals which \xe2\x80\x98x\xe2\x80\x99 is to be cut into *_or_ an interval\n specification, one of \xe2\x80\x98"sec"\xe2\x80\x99, \xe2\x80\x98"min"\xe2\x80\x99, \xe2\x80\x98"hour"\xe2\x80\x99, \xe2\x80\x98"day"\xe2\x80\x99,\n \xe2\x80\x98"DSTday"\xe2\x80\x99, \xe2\x80\x98"week"\xe2\x80\x99, \xe2\x80\x98"month"\xe2\x80\x99, \xe2\x80\x98"quarter"\xe2\x80\x99 or \xe2\x80\x98"year"\xe2\x80\x99,\n optionally preceded by an integer and a space, or followed by\n \xe2\x80\x98"s"\xe2\x80\x99. For \xe2\x80\x98"Date"\xe2\x80\x99 objects only \xe2\x80\x98"day"\xe2\x80\x99, \xe2\x80\x98"week"\xe2\x80\x99,\n \xe2\x80\x98"month"\xe2\x80\x99, \xe2\x80\x98"quarter"\xe2\x80\x99 and \xe2\x80\x98"year"\xe2\x80\x99 are allowed.*\nRun Code Online (Sandbox Code Playgroud)\n\n输入查看源代码cut.POSIXt,相关部分以此开头:
else if (is.character(breaks) && length(breaks) == 1L) {\nRun Code Online (Sandbox Code Playgroud)\n\n您可以采用本节中的代码来满足您的需求。
\n