R从半标准字符串中提取时间分量

Sup*_*e99 7 string time r posixct

建立

我有一列持续时间存储为数据帧中的字符串.我想将它们转换为适当的时间对象,可能是POSIXlt.使用此方法很容易解析大多数字符串:

> data <- data.frame(time.string = c(
+   "1 d 2 h 3 m 4 s",
+   "10 d 20 h 30 m 40 s",
+   "--"))
> data$time.span <- strptime(data$time.string, "%j d %H h %M m %S s")
> data$time.span
[1] "2012-01-01 02:03:04" "2012-01-10 20:30:40" NA
Run Code Online (Sandbox Code Playgroud)

缺少的持续时间被编码"--"并需要转换为NA- 这已经发生但应该保留.

挑战在于字符串会丢弃零值元素.因此,期望的值2012-01-01 02:00:14将是字符串"1 d 2 h 14 s".但是这个字符串NA用简单的解析器解析:

> data2 <- data.frame(time.string = c(
+  "1 d 2 h 14 s",
+  "10 d 20 h 30 m 40 s",
+  "--"))
> data2$time.span <- strptime(data2$time.string, "%j d %H h %M m %S s")
> data2$time.span
[1] NA "2012-01-10 20:30:40" NA
Run Code Online (Sandbox Code Playgroud)

问题

  1. 处理所有可能的字符串格式的"R方式"是什么?或许可以单独测试和提取每个元素,然后重新组合?
  2. POSIXlt是正确的目标类吗?我需要从任何特定的开始时间免费的持续时间,因此添加错误的年和月数据(2012-01-)是令人不安的.

@mplourde肯定有正确的想法w /动态创建格式字符串基于测试日期格式中的各种条件.cut(Sys.Date(), breaks='years')作为基线的添加datediff也很好,但未能解释as.POSIXct() 注意中的一个关键怪癖:我正在使用R2.11基础,这可能已在以后的版本中修复.

as.POSIXct()变化的输出显着取决于是否包含日期组件:

> x <- "1 d 1 h 14 m 1 s"
> y <-     "1 h 14 m 1 s"  # Same string, no date component
> format (x)  # as specified below
[1] "%j d %H h %M m %S s"
> format (y)
[1] "% H h % M %S s"    
> as.POSIXct(x,format=format)  # Including the date baselines at year start
[1] "2012-01-01 01:14:01 EST"
> as.POSIXct(y,format=format)  # Excluding the date baselines at today start
[1] "2012-06-26 01:14:01 EDT"
Run Code Online (Sandbox Code Playgroud)

因此该difftime函数的第二个参数应该是:

  • 如果输入字符串具有日期组件,则为当前年度第一天的开始
  • 在开始目前的一天,如果输入字符串每天有分量

这可以通过更改cut函数的单位参数来完成:

parse.time <- function (x) {
  x <- as.character (x)
  break.unit <- ifelse(grepl("d",x),"years","days")  # chooses cut() unit
  format <- paste(c(if (grepl("d", x)) "%j d",
                    if (grepl("h", x)) "%H h",
                    if (grepl("m", x)) "%M m",
                    if (grepl("s", x)) "%S s"), collapse=" ")

  if (nchar(format) > 0) {
    difftime(as.POSIXct(x, format=format), 
             cut(Sys.Date(), breaks=break.unit),
             units="hours")
  } else {NA}

}
Run Code Online (Sandbox Code Playgroud)

Mat*_*rde 11

difftime对象是可以添加到任一对象POSIXctPOSIXlt对象的持续时间对象.也许你想用这个而不是POSIXlt

关于从字符串到时间对象的转换,您可以执行以下操作:

data <- data.frame(time.string = c(
    "1 d 1 h",
    "30 m 10 s",
    "1 d 2 h 3 m 4 s",
    "2 h 3 m 4 s",
    "10 d 20 h 30 m 40 s",
    "--"))

f <- function(x) {
    x <- as.character(x)
    format <- paste(c(if (grepl('d', x)) '%j d',
                      if (grepl('h', x)) '%H h',
                      if (grepl('m', x)) '%M m',
                      if (grepl('s', x)) '%S s'), collapse=' ')

    if (nchar(format) > 0) {
        if (grepl('%j d', format)) {
            # '%j 1' is day 0. We add a day so that x = '1 d' means 24hrs.
            difftime(as.POSIXct(x, format=format) + as.difftime(1, units='days'), 
                    cut(Sys.Date(), breaks='years'),
                    units='hours')
        } else {
            as.difftime(x, format, units='hours')
        }
    } else { NA }
}

data$time.span <- sapply(data$time.string, FUN=f)
Run Code Online (Sandbox Code Playgroud)

  • 这是另一种在上面计算`format`的方法:`library(gsubfn); format < - paste(strapply(x,"[dhms]",list(d ="%jd",h ="%H h",m ="%M m",s ="%S s"))[ [1]],崩溃="")` (2认同)