如何解决 R 中 Sankey 的未定义列错误?

How to resolve undefined columns error for a Sankey in R?

我正在 R 中使用 networkD3 构建桑基图,但我收到一条错误消息:

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

我的代码如下:

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)

当我 运行 上面的代码时,我收到了错误消息。我看不出问题出在哪里。

看下面我有的数据

来源:

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

目标:

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

值:

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[,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

您在 sankeyNetwork 函数中设置的列名(即 Source = "Source", Target = "Target", Value = "Value", NodeID = "Name")不在您的数据中。您可以在函数参数中设置正确的列名,或者您可以重命名数据中的列以匹配参数,如下所示...

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)