我想使用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
))
))
)
)
)
這裏是deparsed對象:
> 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'中並不容易,因爲這些級別不一致。這就是爲什麼我標記'遞歸'並認爲它可能是方向。不過,如果我錯了,請糾正我。 – Boxuan
我們需要一個遞歸函數,它將採用數據幀和最小值分割,抱歉暫時沒有時間編碼。例如:'df1 < - data.frame(level,value,stringsAsFactors = FALSE);拆分(df1,cumsum(df1 $ level == 1))'然後刪除最小值,並分割下一個最小值,等等。 – zx8754
我也在想這個,但不知道如何標記每個孩子到正確的父母。換句話說,我們如何防止給第一父母標記第二等級2的值。 – Boxuan