2

我有一个大数据集,但让我们举一个玩具示例:

mydata <- data.table(from=c("John", "John", "Jim"),to=c("John", "Jim", "Jack"))

nodesd=unique(c(mydata$from, mydata$to))
nodes <-   create_node_df(  n=length(nodesd), label=nodesd, type=nodesd)
edges <-   create_edge_df(from = mydata$from, to =  mydata$to,  rel = "leading_to")
graph <-   create_graph(  nodes_df = nodes,     edges_df = edges)
render_graph(graph)

但我明白了:

在此处输入图像描述

而不是预期的结果:在此处输入图像描述

我使用第一个 igraph 得到了那个,但我想避免这一步。

更新:

library(data.table)
mydata <- data.table(from=c("John", "John", "Jim"),to=c("John", "Jim", "Jack"), stringsAsFactors = T)

mydata 已经在使用因子。我不需要额外的步骤转换因子。

我可以用 igraph 创建绘图:

library(igraph)
mygraph <- graph_from_data_frame(d=mydata, directed=T)
plot(mygraph)

在此处输入图像描述

或者使用它的对象来构建一个 DiagrammeR 图:

V(mygraph)$label = V(mygraph)$name
V(mygraph)$name = factor(V(mygraph)$name, levels=as.character(V(mygraph)$name))
mygraph2 <- from_igraph(mygraph)
render_graph(mygraph2)

在此处输入图像描述

但现在我尝试直接从 Diagrammer 做,没有 igraph:

nodesd = unique(unlist(mydata[,.(from,to)]))
nodes <-   create_node_df(  n=length(nodesd), label=nodesd)
edges <-   create_edge_df(from = mydata$from, to =  mydata$to,  rel = "leading_to")
graph <-   create_graph(  nodes_df = nodes, edges_df = edges)
render_graph(graph)

在此处输入图像描述

有什么问题?

4

1 回答 1

1

使用您的第一个代码,我得到:

> mydata <- data.table(from=c("John", "John", "Jim"),to=c("John", "Jim", "Jack"))
> nodesd=unique(c(mydata$from, mydata$to))
> nodes <-   create_node_df(  n=length(nodesd), label=nodesd, type=nodesd)
> edges <-   create_edge_df(from = mydata$from, to =  mydata$to,  rel = "leading_to")
Warning messages:
1: In create_edge_df(from = mydata$from, to = mydata$to, rel = "leading_to") :
  NAs introduced by coercion
2: In create_edge_df(from = mydata$from, to = mydata$to, rel = "leading_to") :
  NAs introduced by coercion
> graph <-   create_graph(  nodes_df = nodes,     edges_df = edges)
> render_graph(graph)

正如@user20650 所说,这是性格和因素的问题。所以我做出改变。

mydata <- data.frame(from=c("John", "John", "Jim"),
                     to=c("John", "Jim", "Jack"))
mydata$from <- as.character(mydata$from)
mydata$to <- as.character(mydata$to)
nodesd = unique(c(mydata$from, mydata$to))
nodes <- create_node_df(  n=length(nodesd), label=nodesd, type=nodesd)
edges <- create_edge_df(from = factor(mydata$from, levels = nodesd),
                        to =  factor(mydata$to, levels = nodesd),
                        rel = "leading_to")
graph <- create_graph(nodes_df = nodes, edges_df = edges)
render_graph(graph)

我得到了下面的结果。

结果:

在此处输入图像描述

我希望它可以帮助。

于 2018-12-28T07:42:27.360 回答