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

如何用tidyverse在RStudio中扩宽订单数据集并添加复购标识

使用tidyverse处理订单复购数据的方案

首先将你提供的样本数据转换为tidyverse友好的tibble格式,并把时间列转为标准时间类型:

library(tidyverse)

# 重构样本数据为tibble并处理时间格式
dat_sample <- tibble(
  customer = c(rep("Jack", 3), "Ann", rep("Alice", 2), "Mark", "Grace"),
  order_time = ymd_hms(c(
    "2018-10-03 19:51:51",
    "2018-10-05 19:55:15",
    "2018-11-19 06:26:02",
    "2019-01-06 15:24:30",
    "2018-10-01 15:15:43",
    "2018-10-05 11:12:54",
    "2019-01-27 00:49:19",
    "2018-10-03 10:10:34"
  ))
)

1. 新增复购标记变量 + 2. 统计客户总下单次数

方式一:保留每笔订单的长格式数据

如果需要保留原始的每笔订单记录,同时附加客户的下单次数和复购标记:

dat_long_with_metrics <- dat_sample %>%
  group_by(customer) %>%
  mutate(
    total_orders = n(),  # 统计每个客户的总下单次数
    whether_to_purchase = if_else(total_orders >= 2, 1, 0)  # 1=复购,0=未复购
  ) %>%
  ungroup()

# 查看结果
print(dat_long_with_metrics)

方式二:客户级别的汇总数据

如果只需要每个客户一行的汇总信息:

customer_summary <- dat_long_with_metrics %>%
  distinct(customer, total_orders, whether_to_purchase) %>%
  arrange(desc(total_orders))

# 查看结果
print(customer_summary)

3. 将长格式转为宽格式

通过pivot_wider将每个客户的多笔订单时间拆分为单独列,同时整合汇总信息:

dat_wide <- dat_sample %>%
  group_by(customer) %>%
  mutate(order_seq = str_c("order_", row_number())) %>%  # 生成订单序号(order_1、order_2...)
  pivot_wider(
    names_from = order_seq,
    values_from = order_time,
    values_fill = NA_DATETIME  # 无对应订单的位置填充NA时间类型
  ) %>%
  left_join(customer_summary, by = "customer") %>%  # 合并汇总统计信息
  select(customer, total_orders, whether_to_purchase, everything())  # 调整列顺序,把核心信息放前面

# 查看宽格式结果
print(dat_wide)

执行后得到的宽格式数据会呈现每个客户的总下单次数、复购标记,以及每笔订单的具体时间,和Excel的多列订单格式一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:15:56