【问题标题】:Convert milliseconds numeric to time MM:SS then sum将毫秒数转换为时间 MM:SS 然后求和
【发布时间】:2019-10-05 16:20:20
【问题描述】:

建议替代 hms 包将数字转换为 MM:SS,这将提供与 difftime 不同的类。

以下面的例子为例,我想将data.frame中的变量y(目前以毫秒为单位)转换为时间格式MM:SS,以便以后求和。

library(hms)

x <- c('a','b')
y = c(256733,249800)
z <- data.frame(x,y)

z$y <- z$y/1000

z$y  <- as.hms(z$y)
class(z$y)

sum(z$y)

目前返回...

506.533 秒的时差

时间变量最终应该是:

04:16 04:09

sum(z$y) = 08:26

【问题讨论】:

    标签: r class datetime time


    【解决方案1】:

    您可以使用 lubridate 包。 dplyr 包只是为了方便数据操作。

    library(lubridate)
    library(dplyr)
    
    # 1 milisecond = 0.001 second
    mili_sec <- 0.001
    
    x <- c('a','b')
    y <- c(256733,249800)
    z <- data.frame(x,y)
    z <- z %>% 
      dplyr::mutate(y = y*mili_sec,
                    y = lubridate::seconds_to_period(y),
                    y = lubridate::parse_date_time(y, "%M %S"),
                    H = base::format(y,"%M"),
                    S = base::format(y,"%S"))
    z
    
    > z
      x                   y  H  S
    1 a 0000-01-01 00:04:17 04 17
    2 b 0000-01-01 00:04:10 04 10
    
    endM <- sum(as.numeric(z$H))
    endS <- sum(as.numeric(z$S))
    base::format(lubridate::parse_date_time(paste(endM, endS), "%M %S"), "%M:%S")
    
    [1] "08:27"
    

    【讨论】:

    • 你甚至可以使用round(seconds_to_period(milliseconds(y)))跳过第一步。
    【解决方案2】:

    另一个选项是使用lubridate::dmilliseconds

    z$y1 <- dmilliseconds(z$y)
      x      y                       y1
    1 a 256733 256.733s (~4.28 minutes)
    2 b 249800   249.8s (~4.16 minutes)
    
    > sum(z$y1)
    [1] 506.533
    

    使用seconds_to_periody1 转换为MM:SS 格式。

    【讨论】:

      猜你喜欢
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-09
      • 2016-03-04
      • 2013-03-09
      • 1970-01-01
      相关资源
      最近更新 更多