【问题标题】:Rounding duration or period to full minutes with lubridate使用 lubridate 将持续时间或周期四舍五入到整分钟
【发布时间】:2020-11-20 13:03:09
【问题描述】:

有没有人有更简洁的方法将 lubridate period 和 duration 对象舍入到分钟而不是秒。

例如,我有以下代码管道:

seconds(x = 3600115) %>% as.duration() %>%  as.period()

这将导致:41d 16H 1M 55S。我想将其四舍五入,使其变为:41d 16H 2M 0S

有没有人知道比以下更好的方法:

(seconds(x = 3600115) / 60) %>% as.numeric() %>% round() %>% dminutes() %>% as.period()

这会导致:41d 16H 2M 0S

【问题讨论】:

    标签: r date time lubridate


    【解决方案1】:

    持续时间对象以数字形式存储为秒数,周期对象可以使用period_to_seconds() 方便地转换为秒数,因此您可以使用一个简单的函数:

    library(lubridate)
    
    # Create period object
    p <- seconds_to_period(3600115)
    
    # Create duration object
    d <- as.duration(p)
    
    minround <- function(x) {
      stopifnot(is.period(x) || is.duration(x))
      if (is.duration(x))
        round(x / 60) * 60
      else
        seconds_to_period(round(period_to_seconds(x) / 60) * 60)
    }
    
    minround(p)
    # [1] "41d 16H 2M 0S"
    
    minround(d)
    # [1] "3600120s (~5.95 weeks)"
    

    【讨论】:

      【解决方案2】:

      基本 R 选项:

      as.POSIXct(3600115 - 86400, origin = '1970-01-01', tz = 'UTC') %>%
        round('mins') %>%
        format('%jd %HH %MM 0S')
      
      #[1] "041d 16H 02M 0S"
      

      注意事项 -

      • 使用管道以提高可读性。
      • 输出是字符串对象而不是句点对象。

      【讨论】:

      • 感谢您的贡献。我更喜欢最后的解决方案,因为它是一个周期对象。
      • @Jochem 您可以在上面的答案中添加%&gt;% as.period(),以便最后将输出作为周期对象。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-17
      • 2015-01-17
      • 2022-01-02
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 2011-01-22
      相关资源
      最近更新 更多