You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何计算R语言lubridate包中period类型数据的平均值

lubridate包period类型平均值计算方法

错误原因

lubridate的period是由年、月、日、时、分、秒等多时间分量组成的复合类型,base R的mean()函数未适配该数据结构,直接调用会得到错误结果。

正确计算逻辑

  • 先通过period_to_seconds()将period类型转换为统一的数值型总秒数
  • 对总秒数计算平均值
  • 再通过seconds_to_period()将平均秒数转换回period类型

可运行示例代码

library(lubridate)
library(dplyr)

# 构造示例数据
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')))

# 正确计算period平均值
tbl %>% summarise(mean_val = seconds_to_period(mean(period_to_seconds(time_period))))

上述代码运行后得到的平均时长为1H 11M 55S,结果符合预期。

内容的提问来源于stack exchange,提问作者SiH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 16:48:02