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

如何在R语言的DataFrame中构建产品运输路线数据

R语言中整理产品运输路线数据结构问题解决办法

你遇到的问题核心是原数据里的end_point在不同step下含义不同——step1对应的end_point是中间节点,而我们需要的最终终点是step2对应的end_point,同时要把每个产品的step1起点和所有对应的step2终点配对。

直接用pivot_wider失败的原因是没有拆分step1和step2的逻辑,导致end_point列的信息被混淆。下面是可行的解决方案:

步骤说明

  • 先单独提取每个产品的step1起点信息;
  • 再提取step2对应的中间站点和最终终点;
  • 通过product_code将两者关联,得到目标结构。

完整代码

library(dplyr)

# 生成示例数据
end_point <- c("DC_Frankfurt","F6_DC_Bordeaux","B3_Paris","BEAG_Toronto","DC_Frankfurt")
product_code <- c("000001","000001","000001","000002","000002")
site <- c("Plant1","DC_Frankfurt","DC_Frankfurt","DC_Frankfurt","Plant2")
step <- c("step1","step2","step2","step2","step1")

df <- data.frame(end_point, product_code,site,step)

# 提取step1的站点信息(每个产品唯一)
step1_data <- df %>%
  filter(step == "step1") %>%
  select(product_code, step1 = site)

# 提取step2的站点和对应的最终终点
step2_data <- df %>%
  filter(step == "step2") %>%
  select(product_code, step2 = site, end_point)

# 关联得到结果
result <- step1_data %>%
  inner_join(step2_data, by = "product_code")

# 查看结果
print(result)

输出结果

运行后得到的result和你期望的result_expected完全一致:

product_code step1        step2        end_point
1       000001 Plant1 DC_Frankfurt F6_DC_Bordeaux
2       000001 Plant1 DC_Frankfurt      B3_Paris
3       000002 Plant2 DC_Frankfurt   BEAG_Toronto

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:50:27