为边缘名称子集igraph对象

时间:2017-12-04 22:22:18

标签: r subset igraph

考虑一个将每个变量相互关联的数据框:

iris_cor <- structure(list(x = c("Sepal.Length", "Sepal.Length", "Sepal.Length", 
"Sepal.Length", "Sepal.Width", "Sepal.Width", "Sepal.Width", 
"Sepal.Width", "Petal.Length", "Petal.Length", "Petal.Length", 
"Petal.Length", "Petal.Width", "Petal.Width", "Petal.Width", 
"Petal.Width"), y = c("Sepal.Length", "Sepal.Width", "Petal.Length", 
"Petal.Width", "Sepal.Length", "Sepal.Width", "Petal.Length", 
"Petal.Width", "Sepal.Length", "Sepal.Width", "Petal.Length", 
"Petal.Width", "Sepal.Length", "Sepal.Width", "Petal.Length", 
"Petal.Width"), r = c(NA, -0.117569784133002, 0.871753775886583, 
0.817941126271576, -0.117569784133002, NA, -0.42844010433054, 
-0.366125932536439, 0.871753775886583, -0.42844010433054, NA, 
0.962865431402796, 0.817941126271576, -0.366125932536439, 0.962865431402796, 
NA)), row.names = c(NA, -16L), class = c("tbl_df", "tbl", "data.frame"
), .Names = c("x", "y", "r"))

如果我想制作一个网络图,我会做以下事情:

library(igraph)
iris_igraph <- graph_from_data_frame(iris_cor)

现在,如果我只对与Sepal.Length有关的相关性感兴趣,我不清楚如何有效地提取该信息。尝试这两种方法都不成功。第一个是因为错误,第二个是因为我只获得Sepal.Length的第一个实例而不是所有这些:

> subgraph.edges(iris_igraph, E(iris_igraph)[name == "Sepal.Length"])
Error in eval(x$expr, data, x$env) : object 'name' not found
> 
> subgraph.edges(iris_igraph, V(iris_igraph)[name == "Sepal.Length"])
IGRAPH dc7408b DN-- 1 1 -- 
+ attr: name (v/c), r (e/n)
+ edge from dc7408b (vertex names):
[1] Sepal.Length->Sepal.Length

这会产生所需的输出:

subgraph.edges(iris_igraph, E(iris_igraph)[1:4])

然而,当igraph对象的所需子集不按顺序或存在许多节点/边时,编号索引是不实用的。

任何人都可以推荐一种方法来为igraph对象分配边缘名称吗?

1 个答案:

答案 0 :(得分:4)

根据indexing edge sequences,您可以使用特殊函数inc进行边缘子集化,其中:

采用顶点序列,并选择顶点序列中至少有一个入射顶点的所有边。

E(iris_igraph)[inc('Sepal.Length')]
#+ 7/16 edges (vertex names):
#[1] Sepal.Length->Sepal.Length Sepal.Length->Sepal.Width  Sepal.Length->Petal.Length
#[4] Sepal.Length->Petal.Width  Sepal.Width ->Sepal.Length Petal.Length->Sepal.Length
#[7] Petal.Width ->Sepal.Length

Sepal.Length选择边缘:

E(iris_igraph)[from('Sepal.Length')]
#+ 4/16 edges (vertex names):
#[1] Sepal.Length->Sepal.Length Sepal.Length->Sepal.Width  Sepal.Length->Petal.Length
#[4] Sepal.Length->Petal.Width 

选择Sepal.Length的边:

E(iris_igraph)[to('Sepal.Length')]
#+ 4/16 edges (vertex names):
#[1] Sepal.Length->Sepal.Length Sepal.Width ->Sepal.Length Petal.Length->Sepal.Length
#[4] Petal.Width ->Sepal.Length