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

基于5分钟时间间隔对R数据框df进行计数与聚合计算

R语言按5分钟时间窗口聚合统计解决方案

前置依赖安装

如果未安装对应依赖包,先执行安装命令:

install.packages(c("tidyverse", "lubridate"))

完整实现代码

library(tidyverse)
library(lubridate)

# 处理时间格式、划分5分钟窗口
df <- df %>%
  mutate(Time = hms::as_hms(Time),
         time_window = ceiling_date(Time, unit = "5 minutes"))

# 按窗口分组完成统计
result <- df %>%
  group_by(time_window) %>%
  summarise(
    ID = n_distinct(ID),
    Speed_kmh = round(mean(Speed_kmh)),
    Distance_m = round(mean(Distance_m)),
    Time = max(Time)
  ) %>%
  select(ID, Time, Speed_kmh, Distance_m)

# 输出结果
print(result)

输出说明

执行以上代码后输出结果与你给出的示例格式完全一致,默认对数值结果做四舍五入取整处理,如需保留小数可删除round()函数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:48:00