r - 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?我的实际网络有数千个节点,所以我需要自动化这个过程。
解决方案
可能有一种更简单的方法可以做到这一点,但我认为这可能会给你想要的东西。我稍微扩展了您的示例以添加多个案例。
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)
推荐阅读
- arrays - 如何将数字输入到向量中,直到我按下回车键
- c# - Unity:如何将一个对象放在另一个对象之上
- c# - 我可以通过 Microsoft LiveID 帐户“安静地”登录嵌入式 PowerApp 吗?
- java - Watcher 中的空哈希映射值
- xml - XML XSLT 删除节点中的空间
- google-chrome - 为什么当我单击链接时我的网络浏览器不发送 cookie,但是当我输入 url 时它发送它们就好了
- php - 同一应用程序中的大量 sqlite 数据库
- python - Google Ads API - “失败,状态为“PERMISSION_DENIED” - “用户无权访问客户。”
- javascript - 如何使用未在 React-Table 中连续显示的数据?
- isabelle - 如何在 Isabelle/HOL 中使用“THE”语法?