Reputation: 35
I have a graph that each nodes and edges have their own attribute (for example, nodes have different elevation, and edges have different diameters and lengths).
Now, I want to add new nodes in the middle of each edge, and assign the mean elevation of the two connected nodes to pipe, to the new node. I prefer to do these on loop in case of a network with a lot of nodes and edges.
Here's a simple graph exported from R. Use the command below to load it to R:
library(igraph)
g = readRDS("g.rds")
plot (g)
These nodes have different elevations and the edges have different lengths and diameters, but It seems I couldn't export them with the "g.rds", so run the code below to add these attributes:
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")
Upvotes: 2
Views: 115
Reputation: 101247
You can try the code below using 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"))
Upvotes: 5