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

R语言中如何基于现有列值创建新列:按trip_id分组提取行程首尾记录生成汇总数据集

行程首尾信息提取实现方案

本方案完全适配你提供的data.table格式数据集,可直接落地运行。

核心逻辑

按trip_id分组前先对组内记录按时间升序排序,提取每组首行作为行程起点、末行作为行程终点,映射为要求的输出字段。

方案1:data.table原生实现(性能最优,适配原数据结构)

原数据已经是data.table类,直接调用原生分组语法即可,无需额外加载重型依赖:

# 先按行程ID、时间排序,保证首末行匹配时间先后
my.df <- my.df[order(trip_id, time)]

# 分组提取首尾字段
trip_summary <- my.df[, .(
  start_location_Long = first(location_lon),
  start_location_Lat = first(location_lat),
  end_location_Long = last(location_lon),
  end_location_Lat = last(location_lat),
  start_time = first(time),
  end_time = last(time),
  from_vehicle_id = first(vehicle_id)
), by = trip_id]

# 如需转换为tibble格式,运行以下代码
trip_summary <- tibble::as_tibble(trip_summary)

方案2:dplyr实现(易读性强,适配tidyverse生态)

如果你日常使用tidyverse系列工具,可选择该写法:

library(dplyr)

trip_summary <- my.df %>%
  # 按行程ID、时间排序
  arrange(trip_id, time) %>%
  group_by(trip_id) %>%
  summarise(
    start_location_Long = first(location_lon),
    start_location_Lat = first(location_lat),
    end_location_Long = last(location_lon),
    end_location_Lat = last(location_lat),
    start_time = first(time),
    end_time = last(time),
    from_vehicle_id = first(vehicle_id),
    .groups = "drop" # 自动解除分组,避免后续处理报错
  )

关键注意事项

  • 排序步骤不能省略:如果组内记录不是按时间顺序排列,直接取首末行会出现起点、终点和对应时间错配的问题
  • 同一trip_id下的记录属于同一车辆,from_vehicle_id直接取组内第一条的vehicle_id值即可,无需额外校验
  • 示例数据集运行完成后,输出结果和你提供的参考结构完全匹配,仅因示例数据的经纬度是精确小数形式,不会像参考示例那样做四舍五入的占位展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 12:54:03