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

时间:2013-12-13 02:36:26

标签: r networking graph igraph

我使用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属性值发生更改,则第二个图形中所选节点的属性值也应更改(反之亦然)。

有人可以提出如何实现这个目标的解决方案吗?

非常感谢。

1 个答案:

答案 0 :(得分:2)

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

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

因此,图a中的节点1随机地与图b的节点7相关联,映射的节点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

完成工作。