繁体   English   中英

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

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

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

我在平面上有一个tree igraph object 和预定义的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() function 得到图的边列表,我将使用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)

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

你可以试试这个

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

我不知道是否有现有的方法可以做到这一点,但是写一个帮助程序 function 来做这件事并不太费力

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 object 和你的布局来调用它

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM