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

如何在R中按City与对应Neigh的关联关系排序列表splt

实现列表排序:让城市与其最近邻相邻

假设你已经通过eurodist数据集得到了包含城市(作为列表元素名)及其对应最近邻相关数据的列表splt,要实现每个城市与其最近邻相邻且城市在前的排序,可以按以下步骤操作:

1. 确认/生成城市-最近邻映射

首先需要明确每个城市对应的最近邻城市。如果还没有这个映射,可以从eurodist直接生成:

data(eurodist)
# 转换为距离矩阵
dist_matrix <- as.matrix(eurodist)
# 生成每个城市的最近邻映射(排除自身距离)
neighbor_map <- apply(dist_matrix, 1, function(row) {
  row[row == 0] <- Inf  # 把自身距离设为无穷大,避免选中自己
  names(which.min(row))  # 返回距离最小的城市名
})

如果你的splt已经隐含了这个映射(比如每个列表元素的逻辑对应着最近邻),可以直接复用你已有的映射关系替换上面的neighbor_map。

2. 生成排序后的城市序列

通过循环遍历,维护已处理的城市集合,确保每个城市及其未处理的最近邻被按顺序加入:

processed_cities <- character(0)
sorted_city_order <- character(0)

for (city in names(neighbor_map)) {
  if (!city %in% processed_cities) {
    # 添加当前城市
    sorted_city_order <- c(sorted_city_order, city)
    processed_cities <- c(processed_cities, city)
    
    # 获取当前城市的最近邻
    neighbor <- neighbor_map[city]
    # 如果最近邻未被处理,也加入序列
    if (!neighbor %in% processed_cities) {
      sorted_city_order <- c(sorted_city_order, neighbor)
      processed_cities <- c(processed_cities, neighbor)
    }
  }
}

3. 对原列表重新排序

用生成的有序城市序列索引原列表splt,得到目标列表splt_sort:

splt_sort <- splt[sorted_city_order]

说明

  • 这个方法会自动处理双向最近邻(比如A的最近邻是B,B的最近邻是A),只会将这对城市按A,B的顺序加入一次。
  • 如果遇到链式的最近邻关系(如A→B→C→D),会依次将A,B、C,D这类成对组合加入序列,保证每个城市都紧跟自己的最近邻。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:41:28