在 R 中:有没有办法为两组不同长度的节点渲染图形?

In R: is there a way to render a graph for two groups of nodes with different lengths?

我想从两组不同的节点生成一个图表,它们具有不同的长度。您可以在下面找到代码。

如您所见,我收到一条错误消息:错误:length(from) == length(to) is not TRUE !! 这个有解决办法吗?

非常感谢你的帮助!!

library(DiagrammeR)
g1<- c("a","b","c")
g2<-c("d","f")

#creating a node data frame
nodes1<- create_node_df(n=length(g1),
                   style= "filled",
                   color= "lightblue",
                   shape= "box")

nodes2<- create_node_df(n=length(g2),
                    style= "filled",
                    color= "lightblue",
                    shape= "box")
edges<-create_edge_df(from = g1,
                  to= g2,
                  rel= "related",
                  color= "black")

Error: length(from) == length(to) is not TRUE



all_nodes<- combine_ndfs(nodes1, nodes2)

create_graph(nodes_df = all_nodes,
                                    edges_df = edges,
                                    directed = TRUE)

我怀疑你的意思是将 g1 的每个顶点与 g2 的每个顶点连接起来。定义好nodes1nodes2后,让

(all_nodes <- combine_ndfs(nodes1, nodes2))
#   id type label  style     color shape
# 1  1 <NA>  <NA> filled lightblue   box
# 2  2 <NA>  <NA> filled lightblue   box
# 3  3 <NA>  <NA> filled lightblue   box
# 4  4 <NA>  <NA> filled lightblue   box
# 5  5 <NA>  <NA> filled lightblue   box

由于稍后我们将在 create_graph 中使用此变量,我们希望将 1、2、3 中的每一个与 4 和 5 中的每一个连接起来。为 create_edge_df 构建适当的参数我们将使用 rep;那是因为,正如 ?create_edge_df 所说,

from - a vector of node ID values from which edges are outbound. The vector length must equal that of the to vector.

to - a vector of node ID values to which edges are incoming. The vector length must equal that of the from vector.

所以,

edges <- create_edge_df(from = rep(1:3, 2), to = rep(4:5, each = 3),
                        rel = "related", color = "black")
create_graph(nodes_df = all_nodes, edges_df = edges, directed = TRUE)