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

基于环状统计计算POSIXct时间均值并适配dplyr管道的实现方案

可集成dplyr管道的环状日时间均值计算方案

核心自定义函数

你可以直接使用下面封装好的函数,仅需依赖你已经在使用的tidyverse、lubridate、psych三个包,无需额外依赖:

library(tidyverse)
library(lubridate)
library(psych)

mean_time_of_day <- function(time_vec, output = c("hms", "decimal")) {
  # 输入校验
  stopifnot("输入必须为POSIXct类型时间" = inherits(time_vec, "POSIXct"))
  output <- match.arg(output)
  
  # 一步计算十进制小时,向量化运算无需rowwise
  dec_hour <- hour(time_vec) + minute(time_vec)/60 + second(time_vec)/3600
  # 计算环状均值
  mean_dec <- circadian.mean(dec_hour)
  
  # 按要求返回结果
  if (output == "decimal") {
    return(mean_dec)
  } else {
    # 十进制小时转HH:MM:SS格式
    mean_period <- seconds_to_period(round(mean_dec * 3600))
    return(sprintf("%02d:%02d:%02d", mean_period@hour, minute(mean_period), second(mean_period)))
  }
}

使用示例

基础调用

用你提供的示例数据测试,直接调用函数即可得到结果:

df <- data.frame(datetime = as.POSIXct(c("2019-07-14 23:00:17",
                                        "2019-07-14 23:40:20",
                                        "2019-07-14 00:12:45",
                                        "2019-07-14 00:17:19"), tz = "UTC"))

# 输出HH:MM:SS格式
mean_time_of_day(df$datetime)
# 输出十进制小时格式
mean_time_of_day(df$datetime, output = "decimal")

dplyr管道中调用(支持分组)

完全适配dplyr工作流,分组场景也可直接使用:

# 单组统计
df %>% 
  summarise(avg_time = mean_time_of_day(datetime))

# 多组分群统计示例
df %>% 
  mutate(group = c(1,1,2,2)) %>% 
  group_by(group) %>% 
  summarise(avg_time = mean_time_of_day(datetime))

优化说明

  • 砍掉了冗余的多步列生成、rowwise运算逻辑,仅用一行向量化运算完成十进制小时转换,运算效率提升明显
  • 封装后的函数可直接在summarise中调用,无需单独提取向量,完全适配dplyr管道工作流
  • 支持两种输出格式,可按需选择:
    • 需后续数值计算选decimal十进制格式
    • 需结果展示选hms时分秒格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:15:04