如何使用预定义布局保存 igraph 对象的边列表?

How to save the edge list of igraph object with the predefined layout?

我已经阅读了,但在我的例子中,需要将开始边缘和结束边缘的位置与边缘列表一起保存到一个文件中。

我在平面上有一个 tree igraph 对象和预定义的 mylayout 布局。

tree <- make_tree(5, 2, mode = "undirected")
mylayout <- matrix(c(1, 2, 0, 3, 2, 
                     1, 2, 0, 2, 3), ncol=2)

我添加了一个新属性name

tree <- make_tree(5, 2, mode = "undirected") %>% 
            set_vertex_attr("name", value = seq(1:vcount(tree)))

我通过get.edgelist()函数得到图的边列表,我将使用name属性:

   df1 <- data.frame(V1 = get.edgelist(tree)[,1], 
                  V2 = get.edgelist(tree)[,2], 
#           V1_x = mylayout[as.integer(names(V(tree))), 1],
#           V1_y = mylayout[as.integer(names(V(tree))), 2],
#           V2_x = mylayout[, 1],
#           V2_y = mylayout[, 2],
            stringsAsFactors = FALSE)

问题。如何将节点位置与边的开始和结束位置匹配?

我不知道是否有现成的方法可以做到这一点,但是编写一个辅助函数来做到这一点并不太费力

join_layout <- function(g, layout) {
  edges <- as_edgelist(g)
  idx1 <- match(edges[,1], V(g)$name)
  idx2 <- match(edges[,2], V(g)$name)
  result <- cbind(data.frame(edges),
        layout[idx1, ],
        layout[idx2, ]
  )
  names(result) <- c("V1", "V2", "V1_x", "V1_y", "V2_x","V2_y")
  result
}

基本上我们使用match() 将顶点名称与布局矩阵中的行匹配。您通过传入 igraph 对象和布局

来调用它
join_layout(tree, mylayout)
#   V1 V2 V1_x V1_y V2_x V2_y
# 1  1  2    1    1    2    2
# 2  1  3    1    1    0    0
# 3  2  4    2    2    3    2
# 4  2  5    2    2    2    3

你可以试试这个

get.data.frame(tree) %>%
  cbind(
    split(
      data.frame(mylayout)[match(unlist(.), 1:nrow(mylayout)), ],
      c(col(.))
    )
  )

这给出了

  from to 1.X1 1.X2 2.X1 2.X2
1    1  2    1    1    2    2
2    1  3    1    1    0    0
3    2  4    2    2    3    2
4    2  5    2    2    2    3