gpt4 book ai didi

r - igraph 对象的顶点/节点属性

转载 作者:行者123 更新时间:2023-12-05 03:02:28 26 4
gpt4 key购买 nike

我在 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 视为顶点属性graph_from_dataframe 的 code>vertices 参数。这是正确的还是 df_edgelist 中的第 3 列仍然是边缘属性?

最佳答案

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

更进一步,

If vertices is not NULL then the symbolic edge list given in d is checked to contain only vertex names listed in 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

关于r - igraph 对象的顶点/节点属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54741257/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com