如何在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
相关产品推荐
相关产品推荐

