igraph:添加顶点 = X 创建大小为 1 的簇

igraph: adding vertices = X creating clusters of size = 1

我目前正在解决一些图论问题,但有一个问题我似乎找不到答案。使用以下方法创建图形时:

x <- graph_from_data_frame(el, directed = F, vertices = x)

添加 个顶点 = x 创建大小为 1 的组件。

我想查看集群大小,即提取组件并使用 table 查看大小:

comp <- components(x)
table(comp$csize)

鉴于边缘列表的性质,我希望没有集群的大小 <= 2,因为边缘列表是两个 nodes.If I 运行 完全相同的代码 [=32] 之间的关系=]没有顶点= x,我的table将从大小为2的簇开始。

为什么添加 vertices = x 会这样?

谢谢

编辑:

我的边缘列表有变量:

ID   ID.2  soure 
x1   x2    healthcare
x1   x3    child benefit 

顶点数据框包含节点的一般信息(ID)

 ID   date_of_birth   nationality   

 x1     02/09/1999      French 
 x2     12/12/1997      French 
 x3     22/01/2002      French 

我怀疑正在发生的事情是您的 data.frame 节点元数据 x 中出现了未出现在边缘列表中的 ID。 Igraph 会将这些节点添加为孤立的顶点。下面的一些示例代码可以说明问题:

library(igraph)

# generate some fake data
set.seed(42)
e1 <- data.frame(ID = sample(1:10, 5), ID.2 = sample(1:10, 5))
head(e1)
#>   ID ID.2
#> 1 10    6
#> 2  9    7
#> 3  3    2
#> 4  6    5
#> 5  4    9

# make the desired graph object
x <- graph_from_data_frame(e1, directed = F)

# make some attribute data that only matches the nodes that have edges
v_atts1 <- data.frame(ID = names(V(x)), foo = rnorm(length(names(V(x)))))
v_atts1
#>   ID         foo
#> 1 10 -0.10612452
#> 2  9  1.51152200
#> 3  3 -0.09465904
#> 4  6  2.01842371
#> 5  4 -0.06271410
#> 6  7  1.30486965
#> 7  2  2.28664539
#> 8  5 -1.38886070

g1 <- graph_from_data_frame(e1, directed = FALSE, vertices = v_atts1)

# we can see only groups of size 2 and greater
comp1 <- components(g1)
table(comp1$csize)
#> 
#> 2 3 
#> 1 2

# now make attribute data that includes nodes that dont appear in e1
v_atts2 <- data.frame(ID = 1:10, foo=rnorm(10))
g2 <- graph_from_data_frame(e1, directed = FALSE, vertices = v_atts2) 

# now we see that there are isolated nodes
comp2 <- components(g2)
table(comp2$csize)
#> 
#> 1 2 3 
#> 2 1 2

# and inspecting the number of vertices we see that
# this is because the graph has incorporated vertices
# that appear in the metadata but not the edge list
length(V(g1))
#> [1] 8
length(V(g2))
#> [1] 10

如果你想避免这种情况,你可以尝试 graph_from_data_frame(e1, directed=FALSE, vertices=x[x$ID %in% c(e1$ID, e1$ID.2),]) 这应该将你的元数据子集化为仅连接的顶点。请注意,您可能需要检查您的 ID 是否被编码为具有未出现在数据中的级别的因素。