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



我正在使用R中的networkD3构建Sankey图,但我收到了一个错误消息:

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)

相关内容

  • 没有找到相关文章

最新更新