首页 > 解决方案 > r igraph - 根据节点的公共连接和与第三个节点的相同类型的关系创建节点之间的关系

问题描述

节点A和B当前未连接,如果它们满足两个条件我想连接它们:1)都连接到同一个第三节点;2) 与第三个节点的关系类型相同。假设 A 和 B 是同一个父亲的儿子,那么我想将他们识别为兄弟姐妹。我如何指示 r igraph 创建这个新的领带?举个例子。

edgelist <- read.table(text = "
A C
B C
C D")
graph <- graph.data.frame(edgelist, directed = F)
E(graph)[1]$weight <- 2
E(graph)[2]$weight <- 2
E(graph)[3]$weight <- 1

IGRAPH 0dd6cf1 DNW- 4 3 -- 
+ attr: name (v/c), weight (e/n)
+ edges from 0dd6cf1 (vertex names):
[1] A->C B->C C->D

在此示例中,A 和 B 连接到 C,并且它们的连接的权重为 2。如何将 A 和 B 相互连接但不连接到 D?我的实际网络有数千个节点,所以我需要自动化这个过程。

标签: rigraph

解决方案


可能有一种更简单的方法可以做到这一点,但我认为这可能会给你想要的东西。我稍微扩展了您的示例以添加多个案例。

library(igraph)

options(stringsAsFactors = FALSE)

edgelist <- read.table(text = "
                       A C
                       B C
                       C D
                       D A
                       E C
                       D F
                       D G")

g <- graph.data.frame(edgelist, directed = F)

E(g)$weight <- c(2,2,1,1,2,2,2)

#plot graph, scaling the weights just to make them more obvious
plot(g, edge.width = E(g)$weight*3)

原网

#convert back to edgelist
el <- as.data.frame(get.edgelist(g))
el$weight <- E(g)$weight

ids <- unique(c(el$V1, el$V2))

#select sets of alters of all nodes that have edge weight equal to 2 
y <- lapply(ids, function(id) {

  x <- el[which(el$V1 == id | el$V2 == id),]
  x <- x[which(x$weight == 2),]
  alt_nodes <- setdiff(unique(c(x$V1, x$V2)), id)

})

#select sets that have 2 or more edges with weight 2
ly <- which(unlist(lapply(y, length))>= 2)

#add connections of weight 1 between all of these sets of nodes
res <- lapply(ly, function (i) {

  new_edge <- y[[i]]
  ne <- t(combn(new_edge,2))
  ne <- cbind(ne, rep(1, nrow(ne)))
  colnames(ne) <- names(el)
  el< <- rbind(el, ne)

})

#convert back to graph
g2  <-  graph.data.frame(el, directed  =  F)
E(g2)$weight <- el$weight

plot(g2, edge.width = as.numeric(E(g2)$weight)*3)

添加边缘的网络


推荐阅读