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

如何在R的DataFrame中分别计算客户与订阅用户的总行程时长

实现方案

你可以通过分组聚合的方式直接统计不同用户类型的总行程时长,不需要拆分数据,以下是两种常用实现方式:

方法1:基础R实现

使用aggregate函数直接分组求和,假设你的数据框名为df,用户类型列名为user_type,行程时长列名为trip_duration,代码如下:

# 分组统计总时长
sum_result <- aggregate(trip_duration ~ user_type, data = df, FUN = sum)

# 单独提取客户总时长
customer_total <- sum_result[sum_result$user_type == "Customers", "trip_duration"]
# 单独提取订阅用户总时长
subscriber_total <- sum_result[sum_result$user_type == "Subscriber", "trip_duration"]

方法2:dplyr包实现(语法更简洁)

如果常用tidyverse生态的工具,可以用group_by+summarise组合实现:

# 加载dplyr包
library(dplyr)

# 分组统计总时长
sum_result <- df %>%
  group_by(user_type) %>%
  summarise(total_duration = sum(trip_duration))

# 单独提取对应类型的总时长
customer_total <- sum_result %>% filter(user_type == "Customers") %>% pull(total_duration)
subscriber_total <- sum_result %>% filter(user_type == "Subscriber") %>% pull(total_duration)

注意:如果你的数据列名、用户类型的取值和示例不一致,替换为你实际数据里的对应内容即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:36:04