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

基于For Loop实现互斥穷尽网络分组的R代码调试求助

修正R代码实现接触追踪式网络分组

问题说明

现有R代码用于实现类似接触追踪的网络分组:共享位置或关联对象的个体归为同一组,但代码存在变量拼写错误与逻辑漏洞,导致分组结果错误(例如第三行数据应分配Group 1却得到Group 2)。以下是修正方案。

示例数据集

# 创建示例数据集
df <- data.frame(name = c("a", "a", "b", "b", "b", "c", "c", "d", "d", "e", "e", "f", "g", "g", "h"),
                 location = c(1, 2, 1, 3, 4, 3, 2, 5, 6, 7, 8, 4, 9, 10, 5))

原代码问题分析

  1. 变量拼写错误:
    • row$_name 应为 row$name
    • name_group_id 应为初始化的 name_id
    • location _group_id 变量名包含空格,应为 location_id
  2. 逻辑漏洞:
    • 仅检查name是否存在于name_id,未处理「name不在但location关联已有组」时,需将当前name绑定到该组的情况
    • 未同步更新name与location的分组映射,导致后续同name或同location的行无法正确关联分组

修正后的代码

# 初始化分组映射列表
name_id <- list()
location_id <- list()

# 分组计数器
group_id_counter <- 0

# 遍历数据集实现分组逻辑
for (i in 1:nrow(df)) {
  row <- df[i, ]
  name <- row$name
  location <- row$location
  
  # 先检查当前name是否已有分组
  name_group <- name_id[[name]]
  # 再检查当前location是否已有分组
  loc_group <- location_id[[as.character(location)]]
  
  if (!is.null(name_group)) {
    # name已有分组,直接使用
    group_id <- name_group
    # 同步更新当前location的分组(如果还没绑定)
    if (is.null(loc_group)) {
      location_id[[as.character(location)]] <- group_id
    }
  } else if (!is.null(loc_group)) {
    # location已有分组,使用该分组并绑定当前name
    group_id <- loc_group
    name_id[[name]] <- group_id
  } else {
    # 新建分组
    group_id_counter <- group_id_counter + 1
    group_id <- paste0("Group ", group_id_counter)
    name_id[[name]] <- group_id
    location_id[[as.character(location)]] <- group_id
  }
  
  # 为当前行分配分组ID
  df[i, "group_id"] <- group_id
}

# 查看结果
print(df)

验证结果

运行修正后的代码,得到的结果与预期一致:

name location group_id
1     a        1  Group 1
2     a        2  Group 1
3     b        1  Group 1
4     b        3  Group 1
5     b        4  Group 1
6     c        3  Group 1
7     c        2  Group 1
8     d        5  Group 2
9     d        6  Group 2
10    e        7  Group 3
11    e        8  Group 3
12    f        4  Group 1
13    g        9  Group 4
14    g       10  Group 4
15    h        5  Group 2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:20:47