Setup
我有一列持续时间作为字符串存储在数据框中。我想将它们转换为适当的时间对象,可能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
缺失的持续时间已编码"--"
并需要转换为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
问题
- 处理所有可能的字符串格式的“R Way”是什么?也许单独测试并提取每个元素,然后重新组合?
- POSIXlt 是正确的目标类吗?我需要不受任何特定开始时间影响的持续时间,因此添加错误的年份和月份数据(
2012-01-
)令人烦恼。
Solution
@mplourde 绝对有正确的想法,基于测试日期格式中的各种条件来动态创建格式化字符串。添加的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"
因此,第二个论点difftime
函数应该是:
- 如果输入字符串,则为当年第一天的开始has一天的组成部分
- 的开始current如果输入字符串则为天does not有一天的组成部分
这可以通过更改单位参数来实现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}
}