计算 lubridate 中周期的平均值

calculate mean of period in lubridate

如何计算 lubridateperiod 的平均值?

library(lubridate)

# tibble
tbl <- tibble(time_1 = ymd_hms(c("2021-01-01 12:00:00"), ("2021-01-01 12:12:36"), ("2021-01-01 14:25:45")),
              time_2 = ymd_hms(c("2021-01-01 12:12:36"), ("2021-01-01 14:25:45"), ("2021-01-01 15:35:45")),
              time_period = seconds_to_period(difftime(time_2, time_1, units = 'sec')))

# calculate mean of period (WRONG ANSWER)
tbl %>% summarise(mean_val = mean(time_period))

period 对象似乎不适用于 mean。你可以使用

tbl %>%
  summarise(mean = seconds_to_period(mean(period_to_seconds(time_period))))

获得

# A tibble: 1 x 1
  mean      
  <Period>  
1 1H 11M 55S

要获得另一种表示,您可以尝试

tbl %>%
  summarise(
    mean = seconds_to_period(mean(period_to_seconds(time_period))),
    mean_val = mean(period_to_seconds(time_period)),
    days     = mean_val %/% (60*60*24),
    hours    = mean_val %/% (60*60),
    minutes  = mean_val %/% 60 %% 60 + round((mean_val %% 60)/60),
    value    = paste0(days, "d ", hours, "H ", minutes, "M")
    )

获得

# A tibble: 1 x 6
  mean       mean_val  days hours minutes value    
  <Period>      <dbl> <dbl> <dbl>   <dbl> <chr>    
1 1H 11M 55S     4315     0     1      12 0d 1H 12M

我很确定,lubridate 提供了更好的工具来格式化 Period 对象,但我在这里没有太多经验。