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

在R中将宽数据框转长数据框,同时交换配对内对应值

高效合并带_A/_B后缀列并交换connect值的实现方法

原始数据

example <- data.frame(
  date = as.Date(c('2001-01-01',
                   '2001-01-02',
                   '2001-01-01',
                   '2001-01-02')),
  PID_A = c(1091, 1091, 1037, 1037),
  PID_B = c(2091, 2091, 2037, 2037),
  resp_A = c(3,1,2,4),
  resp_B = c(2,4,3,1),
  connect_A = c(6,2,5,3),
  connect_B = c(5,3,6,2)
)

需求说明

需要将所有带_A/_B后缀的列合并为单一变量列,核心规则:

  • 每个PID的resp值取对应后缀的列(如PID_A取resp_A,PID_B取resp_B)
  • 每个PID的connect值取配对伙伴后缀的列(如PID_A取connect_B,PID_B取connect_A)

期望输出

example_solution <- data.frame(
  date = as.Date(rep(c('2001-01-01',
                       '2001-01-02'),4)),
  PID = c(1091, 1091, 2091, 2091, 1037, 1037, 2037, 2037),
  resp = c(3,1,2,4,2,4,3,1),
  connect = c(5,3,6,2,6,2,5,3)
)

高效实现方法

最直接且高效的方式是拆分A、B两组分别提取所需字段,再合并结果:

library(dplyr)

# 处理A组:提取PID_A、resp_A,配对connect_B
group_A <- example %>%
  select(date, PID = PID_A, resp = resp_A, connect = connect_B)

# 处理B组:提取PID_B、resp_B,配对connect_A
group_B <- example %>%
  select(date, PID = PID_B, resp = resp_B, connect = connect_A)

# 合并两组并按日期、PID排序
example_processed <- bind_rows(group_A, group_B) %>%
  arrange(date, PID)

验证结果与期望输出一致:

all.equal(example_processed, example_solution)
# [1] TRUE

方法优势

该方法逻辑清晰,避免了复杂的格式转换操作,运算效率极高,尤其适合处理大规模数据集。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 15:53:44