DiagrammeR creates an “incorrect” diagram in R

I have code that generates a chart with a chart library in R. For the data source, I use the xlsx file, which you can download from this link

library("xlsx")
df <-xlsx::read.xlsx("animals.xlsx", sheetIndex = 1, header = TRUE, encoding = "UTF-8")

In the first lines, I import the file into R. Then, using col1and col2to create a diagram

uniquenodes <- unique(c(df$col1, df$col2))

library(DiagrammeR)

nodes <- create_nodes(nodes=seq(uniquenodes), type="number", label=uniquenodes)
edges <- create_edges(from=match(df$col1, uniquenodes), to=match(df$col2, uniquenodes), rel="related")
g <- create_graph(nodes_df=nodes, edges_df=edges)
render_graph(g)

After using the code, I get the following image:

enter image description here

When it should look like this:

enter image description here

0
source share
1 answer

Short answer

Change the data import code:

df <-xlsx::read.xlsx("animals.xlsx", 
                     sheetIndex = 1, 
                     header = TRUE, 
                     encoding = "UTF-8",
                     stringsAsFactors = FALSE)

Long explanation

, , . ( xlsx, , , )

df <- data.frame(col1 = c("Cat", "Dog", "Bird"),
                 col2 = c("Feline", "Canis", "Avis"))
uniquenodes <- unique(c(df$col1, df$col2))

uniquenodes
[1] 2 3 1

, , . , . :

df <- data.frame(col1 = c("Cat", "Dog", "Bird"),
                 col2 = c("Feline", "Canis", "Avis"),
                 stringsAsFactors = FALSE)
uniquenodes <- unique(c(df$col1, df$col2))

uniquenodes

library(DiagrammeR)


nodes <- create_nodes(nodes=seq(uniquenodes), type="number", label=uniquenodes)
edges <- create_edges(from=match(df$col1, uniquenodes), to=match(df$col2, uniquenodes), rel="related")
g <- create_graph(nodes_df=nodes, edges_df=edges)
render_graph(g)
+1

Source: https://habr.com/ru/post/1669079/


All Articles