【发布时间】:2016-12-15 05:54:41
【问题描述】:
我想使用 networkD3 可视化一些深度嵌套的数据。在发送到radialNetwork 之前,我不知道如何将数据转换为正确的格式。
这是一些示例数据:
level <- c(1, 2, 3, 4, 4, 3, 4, 4, 1, 2, 3)
value <- letters[1:11]
其中level 表示嵌套的级别,value 是节点的名称。通过使用这两个向量,我需要将数据转换为以下格式:
my_list <- list(
name = "root",
children = list(
list(
name = value[1], ## a
children = list(list(
name = value[2], ## b
children = list(list(
name = value[3], ## c
children = list(
list(name = value[4]), ## d
list(name = value[5]) ## e
)
),
list(
name = value[6], ## f
children = list(
list(name = value[7]), ## g
list(name = value[8]) ## h
)
))
))
),
list(
name = value[9], ## i
children = list(list(
name = value[10], ## j
children = list(list(
name = value[11] ## k
))
))
)
)
)
这是解析后的对象:
> dput(my_list)
# structure(list(name = "root",
# children = list(
# structure(list(
# name = "a",
# children = list(structure(
# list(name = "b",
# children = list(
# structure(list(
# name = "c", children = list(
# structure(list(name = "d"), .Names = "name"),
# structure(list(name = "e"), .Names = "name")
# )
# ), .Names = c("name",
# "children")), structure(list(
# name = "f", children = list(
# structure(list(name = "g"), .Names = "name"),
# structure(list(name = "h"), .Names = "name")
# )
# ), .Names = c("name",
# "children"))
# )), .Names = c("name", "children")
# ))
# ), .Names = c("name",
# "children")), structure(list(
# name = "i", children = list(structure(
# list(name = "j", children = list(structure(
# list(name = "k"), .Names = "name"
# ))), .Names = c("name",
# "children")
# ))
# ), .Names = c("name", "children"))
# )),
# .Names = c("name",
# "children"))
然后我可以将它传递给最终的绘图函数:
library(networkD3)
radialNetwork(List = my_list)
输出将如下所示:
问题:如何创建嵌套列表?
注意:正如@zx8754 所指出的,这个SO post 中已经有一个解决方案,但这需要data.frame 作为输入。由于我的level 不一致,我看不到将其转换为data.frame 的简单方法。
【问题讨论】:
-
@zx8754 添加了
dput(my_list)。另外,输入的数据不是data.frame,把它变成data.frame也不容易IMO,因为级别不一致。这就是为什么我标记recursion并认为这可能是方向。但是,如果我错了,请纠正我。 -
我们需要一个递归函数来获取数据帧并根据最小值进行拆分,抱歉目前没有时间编写代码。类似于:
df1 <- data.frame(level, value, stringsAsFactors = FALSE); split(df1, cumsum(df1$level == 1))然后删除最小值,然后拆分下一个最小值,等等。 -
我也在考虑这个问题,但不确定如何将每个孩子标记为正确的父母。换句话说,我们如何防止将第 2 级 2 值标记为第 1 个父级。
标签: r recursion nested-lists networkd3