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

如何在R中按规则打乱DataFrame行,避免name列连续重复?

基于规则打乱DataFrame行(避免连续相同name)

要实现打乱后name列无连续重复值的需求,你可以用贪心式分组抽取的方法,确保每次选取的行都和上一行的name不同。以下是具体的R实现方案:

基础R实现(无需额外包)

这个方法通过循环从可用分组中随机抽取行,彻底避免连续重复:

# 原始数据
data <- data.frame(
  id = c(3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26),
  name = c("restructuring","restructuring","restructuring","restructuring",
           "control","control","control","control",
           "clitic filler","clitic filler","clitic filler","clitic filler",
           "clitic filler","clitic filler","clitic filler","clitic filler",
           "action filler","action filler","action filler","action filler",
           "action filler","action filler","action filler","action filler")
)

# 按name拆分成分组
groups <- split(data, data$name)

shuffled_rows <- list()
last_selected_group <- NULL

# 循环抽取直到所有行都被选中
while (length(unlist(groups)) > 0) {
  # 筛选出还有剩余行、且不是上一次选中的分组
  available_groups <- names(groups)[sapply(groups, length) > 0 & names(groups) != last_selected_group]
  
  # 随机选一个可用分组(如果只有一个可选则直接用)
  selected_group <- if (length(available_groups) == 1) {
    available_groups
  } else {
    sample(available_groups, 1)
  }
  
  # 从选中分组里随机取一行
  row_index <- sample(seq_along(groups[[selected_group]]), 1)
  shuffled_rows <- c(shuffled_rows, list(groups[[selected_group]][row_index, ]))
  
  # 移除已抽取的行
  groups[[selected_group]] <- groups[[selected_group]][-row_index, ]
  
  # 更新上一次选中的分组
  last_selected_group <- selected_group
}

# 转换为DataFrame
shuffled_data <- do.call(rbind, shuffled_rows)

验证结果

运行以下代码检查是否存在连续重复的name:

# 检查连续行是否有相同name
any(shuffled_data$name[-1] == shuffled_data$name[-nrow(shuffled_data)])

返回FALSE则说明满足需求。

原理说明

这个方法的核心是每次只从与上一行不同的分组中抽取,同时优先保证所有分组的行都能被用完。只要你的数据中,最大分组的行数不超过「其他所有分组行数总和 + 1」(你的数据满足:最大分组8行,其他分组总和4+4+8=16行),就一定能生成符合要求的打乱结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 05:47:32