【问题标题】:Parse Time of irregular format in RR中不规则格式的解析时间
【发布时间】:2017-03-19 09:32:53
【问题描述】:

我有一段时间,

  [1] "9.58"      "19.19"     "43.03"     "1:40.91"   "2:11.96"   "3:26.00"  
  [7] "3:43.13"   "4:44.79"   "7:20.67"   "12:37.35"  "26:17.53"  "26:44"    

其中一些只有十进制的秒数。其中一些有分钟和小时,并用“:”分隔

我希望所有这些都在一个单位中(秒或分钟或小时)。我怎么能在R中做到这一点

【问题讨论】:

  • 该示例所需的输出是什么?
  • 正如我所说,所有时间都以秒或分钟或秒为单位的向量。例如,9.58 将是 9.58,1:40.91 将是 100.91。一切都在几秒钟内。

标签: r datetime time datetime-format


【解决方案1】:

我总是非常不愿意手动解析日期和时间,我对自己的代码的信任远低于其他构建专用工具的测试工作。

所以我会使用lubridate 例如:

library(lubridate)

data <-
  c("9.58", "19.19", "43.03", "1:40.91", "2:11.96", "3:26.00", 
   "3:43.13", "4:44.79", "7:20.67", "12:37.35", "26:17.53", "26:44")

difftime(parse_date_time(data, orders = c("%H %M %OS", "%M %OS", "%OS")), 
         parse_date_time("0", orders = "%S"))

# Time differences in secs
#  [1]    9.580002   19.190002   43.029999  100.910004  131.959999
# [6]  206.000000  223.129997  284.790001  440.669998  757.349998
# [11] 1577.529999 1604.000000

lubridate 提供了提供连续尝试的多种解析格式的有利可能性(此处为c("%H:%M:%OS", "%M:%OS", "%OS"),另请注意,可以省略: 分隔符,以便在输入数据格式不正确的情况下进行更健壮的解析)。
我的解决方案仍然有点“hacky”,因为我无法将它们直接解析为difftimes,而是解析为POSIXct,所以我将它们与0 进行了比较以输出difftimes。

【讨论】:

    【解决方案2】:

    您可以用冒号分隔符: 上的str_split 拆分字符串并将它们转换为秒。

    have <- c("9.58","1:40.91","1:01:02.1")
    
    have_split <- strsplit(have,":")   ## List of times split
    
    convert <- function(x){
        x <- as.numeric(x)
        if(length(x) == 1){               ## Has only seconds
            x                           
        } else if(length(x) == 2){        ## Has seconds and minutes
            out <- x[1]*60+x[2]
        } else if(length(x) == 3){        ## Has seconds, minutes and hours
            out <- x[1]*60^2+x[2]*60+x[3]
        }
    }
    
    sapply(have_split,convert)
    ## [1]    9.58  100.91 3662.10
    

    【讨论】:

      【解决方案3】:

      sub将格式统一成统一格式后的几种方法

      data1 <- sub("^([^:]+:[^:]+)$", "00:\\1", sub("^([0-9]*\\.*[0-9]*)$", "00:00:\\1", data))
      

      1) 使用chron - 将“data1”转换为times 对象,强制转换为numeric 并乘以一天中的秒数,即86400

      library(chron)
      60*60*24*as.numeric(times(data1))
      #[1]    9.58   19.19   43.03  100.91  131.96  206.00
      #[7]  223.13  284.79  440.67  757.35 1577.53 1604.00
      

      2) 使用 lubridate 中的 period_to_seconds - 转换为日期时间对象,然后使用 period_to_seconds 将其更改为秒

      library(lubridate)
      period_to_seconds(hms(data1))
      #[1]    9.58   19.19   43.03  100.91  131.96  206.00
      #[7]  223.13  284.79  440.67  757.35 1577.53 1604.00
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-28
        • 2019-02-16
        相关资源
        最近更新 更多