【问题标题】:Converting date variable as character to numeric in r将日期变量作为字符转换为r中的数字
【发布时间】:2017-12-03 23:07:29
【问题描述】:

我有一个数据框,其中包含一个保存为字符的时间段列,格式如下:

x
[1] "00:17:31.199"          "1 day 01:37:46.22"     "00:43:11.51"           "01:18:37.721" ...

我想将此列的值转换为小时(和小时小数)31/,以便返回列是

[1] 0.28 25.61 0.71 1.3 ...

其中 0.28 是 17/60 小时,25.61 等于 24+1+37/60。请注意,所有内容都保存为字符。我在 baseR 或 lubridate 中找不到任何命令来解决这个问题。有什么帮助吗?

【问题讨论】:

  • 您可以与as.difftime(x, format="%H:%M:%OS", units="hours") 接近,但您将不得不单独处理前面带有n day(s) 的情况。
  • 我可能会使用正则表达式将日期拆分为一个单独的向量,然后您可以按照@thelatemail 的建议将该向量添加回您的 H:M:S 数据中。
  • 这是一种使用grepgsub 的方法:首先获取以天数开头的索引向量:ind <- grep("(\\d+)(?=\\sday).*",x,perl=TRUE),然后提取天数:days <- gsub("(\\d+)(?=\\sday).*","\\1",x,perl=TRUE),然后拔掉那些没有日子的人,days[-ind] <- NA
  • 谢谢!这很有帮助。

标签: r lubridate


【解决方案1】:

所以,我最终基于@Mako212 和@thelatemail 做了以下工作:

days <- gsub("(\\d+)(?=\\sday).*", "\\1", x, perl=TRUE) # extracting the number of days
hours <- gsub(".*(\\S*\\s+\\S+)", "\\1", x, perl=TRUE) # getting rid of days
ind <- grep("(\\d+)(?=\\sday).*", x, perl=TRUE) # getting the indices of elements that have days

然后我使用as.difftime 来计算以小时为单位的时差。

time.hours <- as.difftime(x, format="%H:%M:%OS", units="hours")

现在,我需要以小时为单位计算我在向量days 中提取的天数,并将其添加到time.hours

for (i in ind) {
time.hours[ind] <- as.numeric(days[ind])*24 +
    as.difftime(hours[ind], format="%H:%M:%OS", units="hours")
}

请注意,执行上述循环可能有更有效的方法,但我就是这样做的。

【讨论】:

    猜你喜欢
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 2015-01-23
    • 2021-11-17
    • 1970-01-01
    相关资源
    最近更新 更多