【问题标题】:How to deal with times per distance data in R如何处理R中每距离数据的时间
【发布时间】:2019-05-02 18:36:54
【问题描述】:

我有我有时间的数据,例如11:42.7(格式“%M:%OS”),需要行驶一定距离(例如 3000 m)。现在,我希望能够计算分段时间(例如每 500 m 所需的时间)。

timeVar  <- "11:42.7"
distance <- 3000

我试过这个来计算它:

(strptime(timeVar, "%M.%S")/distance)*500

但这会返回: Ops.POSIXt(strptime(timeVar, "%M.%S"), distance) 中的错误: '/' 没有为“POSIXt”对象定义。

使用 lubridate 包我可以计算出这个:

library(lubridate)
(as.duration(ms(timeVar))/distance)*500

返回 [1] "117.116666666667s (~1.95 分钟)" 但我希望结果采用格式 ("%M:%OS")。有需要处理这个的方法吗?例如,我想在其中一个轴上使用格式绘制数据,但我也想将数据用于回归分析。 POSIXt 格式也有类似的情况。

【问题讨论】:

    标签: r lubridate


    【解决方案1】:

    您可以seconds_to_period(在 lubridate 中)将其设置为分钟/秒。然后,使用sprintf随意格式化,如下:

    time <- seconds_to_period((as.duration(ms(timeVar))/distance)*500)
    
    sprintf('%02d:%2.1f', minute(time), second(time)) # 01:57.1
    #or using paste0
    paste0(minute(time),':',round(second(time),1))  # 1:57.1
    #or if you want it with hours
    paste0(time@hour,':',minute(time),':',round(second(time),1)) # 0:1:57.1
    

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      如果转换为period,则可以使用sprintf

      library(lubridate)
      
      d <- as.period(as.duration(ms(timeVar))/distance*500)
      sprintf('%02d:%2.1f', minute(d), ms(d))
      # "01:57.1"
      

      【讨论】:

        【解决方案3】:

        我找到了使用 hms 包的解决方案:

        library(hms)
        timeVar1 <- strptime(timeVar, "%M:%OS")
        timeVar1 <- as.hms(timeVar1)
        
        split500 <- (timeVar1/distance)*500
        # Time difference of 117.1167 secs
        
        split500 <- as.hms(split500)
        # 00:01:57.116667
        

        【讨论】:

          猜你喜欢
          • 2020-07-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-27
          • 2016-11-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多