目标:使用不同层次结构级别的自定义聚合值将数据转换为树数据结构,以作为r的highcharter
包的输入,以创建交互式{{1 }}
我使用treemap
包手动创建了树,因为它有助于更轻松地操作。这是代码
数据
data.tree
代码
> dput(df)
structure(list(Costcenter = c("N1", "N1", "N1", "N1", "N1", "N1",
"N1", "N1", "N2", "N2", "N2", "N2", "N2", "N2", "N3", "N3", "N4",
"N5", "N5", "N6"), Vendor = c("L2", "L2", "L2", "L2", "L2", "L2",
"L2", "L2", "L1", "L2", "L2", "L2", "L3", "L3", "L2", "L2", "L2",
"L2", "L2", "L2"), absDiff = c(103.0776, 37.9086, 269.7629, 6.0888,
515.388, 27.2604, 27.2604, 6.3608, 4.5434, 88.5966, 982.2193,
139.4249, 0.5452, 722.9811, 130.3381, 147.8434, 271.8786, 88.5966,
327.4065, 366.564), value = c(103.0776, 37.9086, 269.7629, 6.0888,
515.388, 27.2604, 27.2604, 6.3608, 4.5434, 88.5966, 982.2193,
139.4249, 0.5452, 722.9811, 130.3381, 147.8434, 271.8786, 88.5966,
327.4065, 366.564), Tool = c("M1", "M2", "M4", "M5", "M6", "M9",
"M10", "M11", "M8", "M5", "M9", "M10", "M3", "M7", "M4", "M5",
"M5", "M5", "M10", "M5")), .Names = c("Costcenter", "Vendor",
"absDiff", "value", "Tool"), row.names = c(NA, -20L), class = "data.frame")
此代码适用于较小的数据集。但是,当我的数据进入100个节点时,运行时最长可达70秒。我已经确定了 #specify the tree hierarchy
df$pathString <- paste("Root" ,df$Costcenter, df$Vendor, df$Tool, sep = "/")
library("data.tree")
s <- as.Node(df ,mode="table") #<-performance problem
#create values for parent nodes, by aggregation of children values
s$Do(function(node) node$value <- Aggregate(node , attribute = "value", aggFun = sum), traversal = "post-order")
# assign ids to all nodes
s$Set(id = 1:s$totalCount)
# calculate parent ids for all children, using parent1 as parent is system reserved by data.tree
s$Set(parent1 = c(function(self) GetAttribute(self$parent, "id", format = identity)))
#copy the data tree structure to a data.frame
test <- ToDataFrameTree(s,"value", "level", "id","parent1")#<-performance problem
test <- data.table(test)
test[,parent:= as.character(parent1)] # parent and ids should be of character for highcharts
test[,id:=as.character(id)] # parent and ids should be of character for highcharts
test[,value:= as.numeric(trimws(value))]
library(rCharts)
#convert each row to a list
list <- toJSONArray2(test,FALSE)
library(highcharter)
highchart() %>%
hc_add_series(
type = "treemap",
layoutAlgorithm = "squarified",
allowDrillToNode = TRUE,
levels = list(
list(
level = 1,
dataLabels = list(
enabled = TRUE
),
borderWidth = 3
),
list(
level = 2,
dataLabels = list(
enabled = TRUE
),
borderWidth = 2
)
),
data= list
)
和as.node()
函数所关注的领域。请帮我关闭运行时。提前谢谢。