igraph:在每条边的中间添加新节点

rhfm7lfc  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(126)

我有一个图,每个节点和边都有自己的属性(例如,节点有不同的高程,边有不同的直径和长度)。
现在,我想在每条边的中间添加新节点,并将两个连接节点的平均高程分配给管道,分配给新节点。

我更喜欢在循环上执行这些操作,以防网络有很多节点和边。
下面是a simple graph exported from R,使用下面的命令将其加载到R:

library(igraph)
g = readRDS("g.rds")
plot (g)

这些节点有不同的高度和边缘有不同的长度和直径,但似乎我不能用“g.rds”导出它们,所以运行下面的代码添加这些属性:

E(g)$Length = c(1000, 1000, 1000, 1000)
E(g)$Diameter = c(500, 500, 500, 500)
V(g)$Elevation = c(10, 50, 30, 30)

>dput(g):
structure(list(4, FALSE, c(3, 2, 2, 1), c(0, 0, 1, 0), c(3, 1, 
2, 0), c(3, 1, 0, 2), c(0, 0, 1, 3, 4), c(0, 3, 4, 4, 4), list(
    c(1, 0, 1), structure(list(), names = character(0)), list(
        name = c("J-1", "J-2", "J-3", "R-1"), XCoord = c(1248.164, 
        5991.189, 2246.696, -631.424), YCoord = c(5976.505, 5741.557, 
        3113.069, 7621.145), color = c("gray", "gray", "gray", 
        "orange"), shape = c("circle", "circle", "circle", "square"
        ), elevation = c(10L, 50L, 30L, 10L), Elevation = c(10L, 
        50L, 30L, 30L)), list(label = c("P-1", "P-2", "P-3", 
    "P-4"), Diameter = c(500L, 500L, 500L, 500L), Lenght = c(1000L, 
    1000L, 1000L, 1000L), label_no_P = c(1, 2, 3, 4), Length = c(1000L, 
    1000L, 1000L, 1000L))), <environment>), class = "igraph")
wlp8pajw

wlp8pajw1#

您可以使用edgelist尝试以下代码

el <- get.edgelist(g)

pmid <- setNames(
  rowMeans(matrix(V(g)$Elevation[match(el, names(V(g)))], ncol = 2)),
  paste0("P-", 1:nrow(el))
)

w <- c(setNames(V(g)$Elevation, V(g)$name), pmid)

out <- graph_from_edgelist(rbind(
  cbind(el[, 1], paste0("P-", 1:nrow(el))),
  cbind(paste0("P-", 1:nrow(el)), el[, 2])
), directed = FALSE) %>%
  set_vertex_attr(name = "name", value = paste0(V(.)$name, ": ", w[V(.)$name])) %>%
  set_vertex_attr(name = "color", value = startsWith(V(.)$name, "P"))

相关问题