gpt4 book ai didi

r - 将关系数据转换为 R 中的层次结构列表

转载 作者:行者123 更新时间:2023-12-02 11:22:05 25 4
gpt4 key购买 nike

这是我的第一个问题;所以请温柔点。

我有一些以下形式的数据:

library('networkD3')
Relationships<- data.frame(Parent=c("earth","earth","forest","forest","ocean","ocean","ocean","ocean"),
Child=c("ocean","forest","tree","sasquatch","fish","seaweed","mantis shrimp","sea monster"))
> Relationships
Parent Child
1 earth ocean
2 earth forest
3 forest tree
4 forest sasquatch
5 ocean fish
6 ocean seaweed
7 ocean mantis shrimp
8 ocean sea monster

本质上,这是可用于制作网络 map 的边列表:

net <- graph_from_data_frame(d = Relationships,
directed = T)
plot(net)

enter image description here

我想将其转换为可在下面的 diagonalNetwork 函数中使用的形式。

Hierarchical_list <- list(name = "earth",
children = list(list(name = "ocean",
children = list(list(name = "mantis shrimp"),
list(name = "fish"),
list(name = "sea monster"),
list(name = "seaweed")
)),
list(name = "forest",
children = list(list(name = "sasquatch"),
list(name = "tree")
))
))
diagonalNetwork(Hierarchical_list)

像这样:

enter image description here

当我尝试使用此循环生成列表时:

    List_attempt <- list()

levels<- levels(factor(Relationships$Parent))

for(n in 1:length(levels)){
Children <- subset(Relationships, Relationships$Parent == levels[n], select = Child)
for(c in 1:length(Children)){
sublist <- as.list(Children)
List_attempt <- list(List_attempt, name = levels[n],children = sublist)
}
}

diagonalNetwork(List_attempt)

我收到此错误:

Error in FUN(X[[i]], ...) : 
'options' must be a fully named list, or have no names (NULL)

1) 有没有更好的方法为 diagonalNetwork 创建列表?

2)失败;如何修改我的循环以推出正确结构的列表?

3)我应该使用其他功能/包吗?

感谢您提供的任何帮助,我已经把头撞在墙上有一段时间了。也欢迎提出有关 SO 问题的更好方法的反馈。

澄清:

在这里找到了类似的问题,Convert a data frame to a treeNetwork compatible list 。然而,它依赖于一种数据结构,其中根始终位于第一列,其子级位于后续列中,而不是像本问题中那样的边列表,这在 igraph 中常用。

最佳答案

您可以使用 data.tree 包,它可以进行许多开箱即用的分层数据转换:

library('networkD3')
Relationships<- data.frame(Parent=c("earth","earth","forest","forest","ocean","ocean","ocean","ocean"),
Child=c("ocean","forest","tree","sasquatch","fish","seaweed","mantis shrimp","sea monster"))

library('data.tree')
tree <- FromDataFrameNetwork(Relationships)
tree
lol <- ToListExplicit(tree, unname = TRUE)
diagonalNetwork(lol)

关于r - 将关系数据转换为 R 中的层次结构列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36273730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com