2

I'm building a sankey diagram using networkD3 in R but I'm getting an error message:

Error in `[.data.frame`(Links, , Source) : undefined columns selected

The code that I have is the following:

library(networkD3)
library(magrittr)

# Data Sources
file <- c("M://R//SankeyDataACT.csv")
links <- read.csv(file, sep =",", header = TRUE)
file <- c("M://R//SankeyNodes.csv")
nodes <- read.csv(file, sep =",", header = TRUE)
sankeyData <- list(nodes=nodes, links=links)

# Sankeydiagram
sankeyNetwork(Links = sankeyData$links, 
              Nodes = sankeyData$nodes, 
              Source = "Source",
              Target = "Target", 
              Value = "Value", 
              NodeID = "Name",
              units = "$", 
              fontSize = 12, 
              nodeWidth = 30)

When I run the code above I get the error message. I don't see where the problem is.

See below the data I have

Source:

links[,1]
 [1] 0 0 0 1 1 1 2 2 2 2 3 3 3 3 4 4 5 5 5 5 6 6 6 6 6

Target:

links[,2]
 [1]  7  8  9  7  8 10  7  9  8 10  9  7  8 10  7  8 10  8  7  9 11  8  7  9 10

Value:

links[,3]
 [1]   4   8   6   6   2   4  12  12  23  12 148 260 285   3   2   1  67 117 177  34  28  67  20  21   1

Nodes:

nodes[,1]
 [1] ATT BHL CTL MEX MTL SSL TLS CEE SWE NWE MEA MF  OEM
Levels: ATT BHL CEE CTL MEA MEX MF MTL NWE OEM SSL SWE TLS
CJ Yetman
  • 8,373
  • 2
  • 24
  • 56
Selrac
  • 2,203
  • 9
  • 41
  • 84

1 Answers1

2

The column names that you are setting in the sankeyNetwork function (i.e. Source = "Source", Target = "Target", Value = "Value", NodeID = "Name") are not in your data. You can set the proper column names in the functions arguments, or you could rename the columns in your data to match the arguments like so...

names(sankeyData$nodes)[1] <- "Name"
names(sankeyData$links)[1:3] <- c("Source", "Target", "Value")

sankeyNetwork(Links = sankeyData$links, 
              Nodes = sankeyData$nodes, 
              Source = "Source",
              Target = "Target", 
              Value = "Value", 
              NodeID = "Name",
              units = "$", 
              fontSize = 12, 
              nodeWidth = 30)
CJ Yetman
  • 8,373
  • 2
  • 24
  • 56