igraph错误无法创建具有负数顶点的空图

use*_*622 4 r igraph

当我尝试创建下面的简单图表时,为什么会出现错误?如果我用数字替换“a”和“b”,那么它可以工作吗?任何解决方案

g1 <- graph(c("a","b"),directed=TRUE)
Run Code Online (Sandbox Code Playgroud)

错误是

Error in graph(c("a", "b"), directed = TRUE) : 
  At type_indexededgelist.c:117 : cannot create empty graph with negative number of vertices, Invalid value
In addition: Warning messages:
1: In graph(c("a", "b"), directed = TRUE) : NAs introduced by coercion
2: In graph(c("a", "b"), directed = TRUE) : NAs introduced by coercion
Run Code Online (Sandbox Code Playgroud)

jos*_*ber 5

?graph,您可以读到:

edges: Numeric vector defining the edges, the first edge points from the first element to the second, the second edge from the third to the fourth, etc.
Run Code Online (Sandbox Code Playgroud)

由于它正在寻找一个数字向量,但你给了它文本,它会将所有字母转换为NA(这是“强制引入的 NA”。)

您可以使用以下内容将文本转换为适当的数字标识符:

g1 <- graph(as.numeric(factor(c("a","b"))), directed=TRUE)
Run Code Online (Sandbox Code Playgroud)