igraph对象的顶点/节点属性

时间:2019-02-18 06:02:21

标签: r igraph

我正在使用igraph中的网络分析数据 这是一个示例数据框

df_edgelist=structure(list(Nominator = structure(c(6L, 4L, 7L, 8L, 1L, 2L, 
3L, 5L), .Label = c("Andrea", "Dan", "Dan", "Greg", "Jerry", 
"Jim", "Rachel", "Sarah"), class = "factor"), Nominee = structure(c(5L, 
2L, 8L, 1L, 7L, 3L, 6L, 4L), .Label = c("Andrea", "Dan", "Greg", 
"Jeff", "Jerry", "Jerry", "Sarah", "Tim"), class = "factor"), 
    Age_Nominator = c(24L, 25L, 29L, 45L, 43L, 67L, 67L, 45L)), class = "data.frame", row.names = c(NA, 
-8L))

从文档here中,我得到的印象是,graph_from_dataframe函数会将第3列Age_Nominator视为顶点属性,如果我还为其提供了另一个数据框并设置了vertices的{​​{1}}参数中的数据框。是正确的还是graph_from_dataframe中的第三列仍然是edge属性?

1 个答案:

答案 0 :(得分:1)

graph_from_data_frame中感兴趣的两个参数是dvertices。如评论中所述,d中的额外列将是边属性,而vertices中的额外列(其中第一列是顶点名称)将是顶点属性。

进一步

  

如果vertices不是NULL,则检查d中给出的符号边列表,使其仅包含vertices中列出的顶点名称。

表示d的前两列不能提及vertices中不存在的任何顶点。另一方面,如果vertices有一些额外的顶点,那将不会引起任何问题,它们将被孤立。

例如,

df_vertices <- data.frame(someNames = c("NewName", as.character(unique(unlist(df_edgelist[, 1:2])))))
df_vertices$Age <- 20 + 1:nrow(df_vertices)
df_vertices
#    someNames Age
# 1    NewName  21
# 2        Jim  22
# 3       Greg  23
# 4     Rachel  24
# 5      Sarah  25
# 6     Andrea  26
# 7        Dan  27
# 8      Jerry  28
# 9        Tim  29
# 10      Jeff  30

这样,我们考虑了所有必要的顶点并添加了额外的NewName。然后

g <- graph_from_data_frame(df_edgelist, vertices = df_vertices)
# V(g)$Age
#  [1] 21 22 23 24 25 26 27 28 29 30
V(g)$name
#  [1] "NewName" "Jim"     "Greg"    "Rachel"  "Sarah"   "Andrea"  "Dan"     "Jerry"   "Tim"    
# [10] "Jeff"   
E(g)
# + 8/8 edges from 7f024f1 (vertex names):
# [1] Jim   ->Jerry  Greg  ->Dan    Rachel->Tim    Sarah ->Andrea Andrea->Sarah  Dan   ->Greg  
# [7] Dan   ->Jerry  Jerry ->Jeff  

符合预期。如果您想避开这些孤立的顶点,可以使用vertices代替

df_vertices[df_vertices$someNames %in% as.character(unique(unlist(df_edgelist[, 1:2]))), ]
#    someNames Age
# 2        Jim  22
# 3       Greg  23
# 4     Rachel  24
# 5      Sarah  25
# 6     Andrea  26
# 7        Dan  27
# 8      Jerry  28
# 9        Tim  29
# 10      Jeff  30