我有一个大型数据集,但让我们举一个玩具示例:
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)
有什么问题?
答案 0 :(得分: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)
我得到下面的结果。
结果:
我希望它能提供帮助。