在R中连接两个不同随机网络中的两个节点



我使用R(和igraph包)创建了两个随机(Erdos-Renyi)网络,每个网络有10个节点。两个网络中的每个节点都被随机分配了一个属性0或1。

这是我的代码:

# Creates the first Erdos-Renyi graph, graph_a, with 10 nodes and edges with
# p=0.2
num_nodes <- 10
prob <- 0.2
graph_a <- erdos.renyi.game(num_nodes, prob, type=c("gnp", "gnm"),
    directed=FALSE, loops=FALSE)
# Randomly sets the attributes of the nodes of graph_a to either 0 or 1
graph_a <- set.vertex.attribute(graph_a, "value", 
    value = sample(0:1, num_nodes, replace=TRUE))

# Creates the second Erdos-Renyi graph, graph_b, with 10 nodes and edges with 
# p=0.2
graph_b <- erdos.renyi.game(num_nodes, prob, type=c("gnp", "gnm"),
    directed=FALSE, loops=FALSE)
# Randomly sets the attributes of the nodes of graph_b to either 0 or 1
graph_b <- set.vertex.attribute(graph_b, "value", 
    value = sample(0:1, num_nodes, replace=TRUE))

我需要以某种方式将第一个图中随机选择的节点链接到第二个图中的随机选择节点。因此,如果第一个图中选定节点的0或1属性值发生变化,则第二个图中所选节点的属性值也应发生变化(反之亦然)。

有人能就如何实现这一目标提出解决方案吗?

提前非常感谢。

定义从a中的节点到b中的节点的映射-它不一定是排列,只要这是一个长度为10的向量,其中包含条目<=b中将应用的节点数:

> perm=sample(10)
> perm
 [1]  7  6  1  8  5 10  2  9  3  4

因此,图a中的节点1与图b的节点7随机关联,a的节点2映射到b的节点6,依此类推

graph_a:中选择一个随机节点

> i=sample(10,1)
> i
[1] 7  # 7 was picked

目前:

> V(graph_a)$value[i]
[1] 0

所以我们翻转它:

> V(graph_a)$value[i] = 1 - V(graph_a)$value[i]
> V(graph_a)$value[i]
[1] 1

这映射到b中的哪个?

> perm[7]
[1] 2

目前:

> V(graph_b)$value[2]
[1] 1

所以翻转一下:

> V(graph_b)$value[perm[i]] = 1 - V(graph_b)$value[perm[i]]
> V(graph_b)$value[perm[i]]
[1] 0

工作完成了。

最新更新