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

从sf linestring对象生成带正确索引标签的inla.graph邻域对象

解决Linestring转INLA邻域对象并绑定自定义城市编码的方案

方案一:基于sfnetwork修复节点识别问题

你遇到的节点数异常问题核心原因是sfnetwork默认按坐标浮点精度匹配节点,微小精度误差、重复记录都会导致同一城市被识别为多个节点,主动构造唯一节点表即可解决:

library(dplyr)
library(sf)
library(sfnetworks)
library(spdep)
library(INLA)

# 1. 提取所有唯一城市节点,按城市编码去重,保证一个编码对应唯一节点
## 提取起点信息
ori_nodes <- regic_link %>% 
  select(code = origin_code, name = nome_ori) %>% 
  mutate(geometry = st_startpoint(geometry))
## 提取终点信息
dest_nodes <- regic_link %>% 
  select(code = dest_code, name = nome_dest) %>% 
  mutate(geometry = st_endpoint(geometry))
## 合并去重,按城市编码为唯一标识
all_nodes <- rbind(ori_nodes, dest_nodes) %>% 
  distinct(code, .keep_all = T)
# 此时nrow(all_nodes)就是你的实际城市数量,可自行校验是否符合预期

# 2. 手动构造空间网络,主动指定节点和边的关联规则
regic_net <- sfnetwork(
  nodes = all_nodes,
  edges = regic_link,
  directed = F,
  node_key = "code", # 节点的唯一标识字段为城市编码
  edge_key = c("origin_code", "dest_code") # 边的起点终点对应城市编码
)

# 3. 生成符合要求的邻域对象,绑定城市编码为行名
## 生成邻接矩阵,行名列名直接使用城市编码
net_adj <- as_adjacency_matrix(regic_net, attr = "code", names = T)
## 转换为spdep的邻域对象
nb_net <- mat2listw(net_adj, style = "B")$neighbours
## 绑定自定义城市编码为邻域标识,保证和你的数据框匹配
attr(nb_net, "region.id") <- all_nodes$code
names(nb_net) <- all_nodes$code

# 4. 导出为INLA可用的graph文件
dir.create("output", showWarnings = F)
nb2INLA("output/nb_orig.graph", nb_net)

方案二:直接基于边表构造(更稳定,无空间匹配误差)

如果你的regic_link表已经明确记录了所有城市间的邻接关系,可以完全跳过空间节点识别步骤,从根源上避免坐标匹配带来的所有问题:

library(spdep)
library(INLA)

# 1. 提取所有唯一城市编码
all_codes <- unique(c(regic_link$origin_code, regic_link$dest_code))
n_city <- length(all_codes)
# 建立城市编码到数字索引的映射
code_idx <- setNames(1:n_city, as.character(all_codes))

# 2. 构造双向邻接矩阵
adj_mat <- matrix(0, nrow = n_city, ncol = n_city, dimnames = list(all_codes, all_codes))
for (i in 1:nrow(regic_link)) {
  o <- as.character(regic_link$origin_code[i])
  d <- as.character(regic_link$dest_code[i])
  adj_mat[o, d] <- 1
  adj_mat[d, o] <- 1
}

# 3. 转换为邻域对象并导出
nb_net <- mat2listw(adj_mat, style = "B")$neighbours
attr(nb_net, "region.id") <- all_codes
names(nb_net) <- all_codes

dir.create("output", showWarnings = F)
nb2INLA("output/nb_orig.graph", nb_net)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 01:48:01