-1

I have a file with export from source country to target country, the value of the trade is in Before_value dimension. My data is in a data.table with dimensions source and target as character (list of country codes) and beofre_value numeric.

I would like to generate a sankey diagram, using sankeyNetwork() from , with the source countries on the left and the target countries on the right and the flows represented. How do I define the nodes and links data frames properly? I have these lines:

library("networkD3")

sankeyNetwork(Links = IMP$source, Nodes = iMP$target, Source = "source",
              Target = "target", Value = "Before_value", fontSize = 25, 
              nodeWidth = 30, fontFamily = "sans-serif", iterations = 0)

I got his error message: Error in Links[, Source] : incorrect number of dimensions

CJ Yetman
  • 8,373
  • 2
  • 24
  • 56
IRT
  • 209
  • 2
  • 11

1 Answers1

0

I believe you're talking about the sankeyNetwork() function from networkD3, not the plotly package. Assuming that's the case, here is a minimal reproducible example demonstrating your particular use case.

library(networkD3)

IMP <- data.frame(source = c("DEU", "DEU", "DEU", "FRA", "FRA", "FRA"),
                  target = c("ESP", "GBR", "ITA", "ESP", "GBR", "ITA"),
                  Before_value = c(4,2,7,4,1,8))

# create nodes data by determining all unique nodes found in your data
node_names <- unique(c(as.character(IMP$source), as.character(IMP$target)))
nodes <- data.frame(name = node_names)

# create links data by matching the source and target values to the index of the
# node it refers to in the nodes data frame
links <- data.frame(source = match(IMP$source, node_names) - 1,
                    target = match(IMP$target, node_names) - 1,
                    Before_value = IMP$Before_value)

sankeyNetwork(Links = links, Nodes = nodes, Source = "source", 
              Target = "target", Value = "Before_value")

enter image description here

CJ Yetman
  • 8,373
  • 2
  • 24
  • 56