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

如何依据指定列的计数生成含双向配对组合的长数据集

R实现按指定次数生成正反配对长表

实现代码

tidyverse 版本

# 加载依赖包
library(tidyverse)

# 构造示例数据集
df <- structure(list(ID = c(1, 2, 3, 4, 5), COL1 = c("A", "B", "C", 
"D", "E"), COL2 = c("F", "G", "H", "I", "J"), Paired = c(2, 3, 
1, 2, 1)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", 
"data.frame"))

# 处理生成目标长表
result <- df %>%
  rowwise() %>%
  summarise(
    Col = rep(c(COL1, COL2), each = Paired),
    Col2 = rep(c(COL2, COL1), each = Paired),
    .groups = "drop"
  )

base R 版本

无需额外安装依赖:

# 构造示例数据集
df <- structure(list(ID = c(1, 2, 3, 4, 5), COL1 = c("A", "B", "C", 
"D", "E"), COL2 = c("F", "G", "H", "I", "J"), Paired = c(2, 3, 
1, 2, 1)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", 
"data.frame"))

# 处理生成目标长表
result <- do.call(rbind, lapply(1:nrow(df), function(i) {
  pair_cnt <- df$Paired[i]
  rbind(
    data.frame(Col = rep(df$COL1[i], pair_cnt), Col2 = rep(df$COL2[i], pair_cnt)),
    data.frame(Col = rep(df$COL2[i], pair_cnt), Col2 = rep(df$COL1[i], pair_cnt))
  )
}))

效果说明

运行代码后得到的result完全符合规则:每行的正序(COL1在前、COL2在后)和倒序(COL2在前、COL1在后)两种组合分别重复Paired次,总记录数为所有行Paired值总和的2倍。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 08:54:03