此函数从包含(符号)边列表和边/顶点属性的一个或两个数据框创建一个 igraph 图。
用法
as_data_frame(x, what = c("edges", "vertices", "both"))
graph_from_data_frame(d, directed = TRUE, vertices = NULL)
from_data_frame(...)
详细信息
graph_from_data_frame()
从一个或两个数据框创建 igraph 图。它有两种操作模式,具体取决于 vertices
参数是 NULL
还是非 NULL
。
如果 vertices
为 NULL
,则 d
的前两列用作符号边列表,其他列用作边属性。属性的名称取自列的名称。
如果 vertices
不是 NULL
,则它必须是一个提供顶点元数据的数据框。假定 vertices
的第一列包含符号顶点名称,这将作为 “name
” 顶点属性添加到图中。其他列将添加为其他顶点属性。如果 vertices
不是 NULL
,则检查 d
中给出的符号边列表是否仅包含 vertices
中列出的顶点名称。
通常,数据框从 Excel 等电子表格软件导出,并通过 read.table()
、read.delim()
或 read.csv()
导入到 R 中。
数据框中的所有边都包含在图中,其中可能包括多个并行边和循环。
as_data_frame()
根据 what
参数将 igraph 图转换为一个或多个数据框。
如果 what
参数为 edges
(默认值),则返回图的边以及边属性。这些边将位于前两列中,分别命名为 from
和 to
。(这也表示有向图的边方向。)对于命名图,顶点名称将包含在这些列中,对于其他图,则包含数字顶点 ID。边属性将位于其他列中。最好不要将边属性命名为 from
或 to
,因为数据框中命名的列将不是唯一的。边按其数字 ID 的顺序排列。
如果 what
参数为 vertices
,则返回顶点属性。顶点按其数字顶点 ID 的顺序排列。
如果 what
参数为 both
,则顶点和边数据都将返回,在一个具有名为 vertices
和 edges
的条目的列表中。
注意
对于 graph_from_data_frame()
,在创建图之前,前两列 “d” 中的 NA
元素将替换为字符串 “NA”。这意味着所有 NA
将对应于单个顶点。
“vertices” 的第一列中的 NA
元素也被字符串 “NA” 替换,但 “vertices” 的其余部分不会被触及。换句话说,顶点名称(=第一列)不能为 NA
,但其他顶点属性可以。
参见
graph_from_literal()
用于创建图的另一种方法,read.table()
用于从文件中读取表格。
其他转换:as.matrix.igraph()
、as_adj_list()
、as_adjacency_matrix()
、as_biadjacency_matrix()
、as_directed()
、as_edgelist()
、as_graphnel()
、as_long_data_frame()
、graph_from_adj_list()
、graph_from_graphnel()
其他双邻接:graph_from_biadjacency_matrix()
作者
Gabor Csardi csardi.gabor@gmail.com
示例
## A simple example with a couple of actors
## The typical case is that these tables are read in from files....
actors <- data.frame(
name = c(
"Alice", "Bob", "Cecil", "David",
"Esmeralda"
),
age = c(48, 33, 45, 34, 21),
gender = c("F", "M", "F", "M", "F")
)
relations <- data.frame(
from = c(
"Bob", "Cecil", "Cecil", "David",
"David", "Esmeralda"
),
to = c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice"),
same.dept = c(FALSE, FALSE, TRUE, FALSE, FALSE, TRUE),
friendship = c(4, 5, 5, 2, 1, 1), advice = c(4, 5, 5, 4, 2, 3)
)
g <- graph_from_data_frame(relations, directed = TRUE, vertices = actors)
print(g, e = TRUE, v = TRUE)
#> IGRAPH 7e5f121 DN-- 5 6 --
#> + attr: name (v/c), age (v/n), gender (v/c), same.dept (e/l),
#> | friendship (e/n), advice (e/n)
#> + edges from 7e5f121 (vertex names):
#> [1] Bob ->Alice Cecil ->Bob Cecil ->Alice David ->Alice
#> [5] David ->Bob Esmeralda->Alice
## The opposite operation
as_data_frame(g, what = "vertices")
#> name age gender
#> Alice Alice 48 F
#> Bob Bob 33 M
#> Cecil Cecil 45 F
#> David David 34 M
#> Esmeralda Esmeralda 21 F
as_data_frame(g, what = "edges")
#> from to same.dept friendship advice
#> 1 Bob Alice FALSE 4 4
#> 2 Cecil Bob FALSE 5 5
#> 3 Cecil Alice TRUE 5 5
#> 4 David Alice FALSE 2 4
#> 5 David Bob FALSE 1 2
#> 6 Esmeralda Alice TRUE 1 3