从平面列表创建树

时间:2014-03-14 11:43:41

标签: r list tree reduce

假设我们有一个如下列表:

[[1]]
[1] "preserver"

[[2]]
[1] "person, individual"

[[3]]
[1] "organism, being" "causal agent"   

[[4]]
[1] "living thing"    "physical entity"

[[5]]
[1] "unit"   "entity"

[[6]]
[1] "object"

[[7]]
[1] "physical entity"

获得如下:

list("preserver", "person, individual", c("organism, being", "causal agent"), c("living thing", "physical entity"), c("unit", "entity"), "object", "physical entity")

假设此列表的每个元素代表一个树的级别,我正在寻找一种方法来创建这样一个树

例如,在这种情况下,输出树将是:

[[1]]
[[1]]$o
[1] "preserver"

[[1]]$h
[[1]]$h[[1]]
[[1]]$h[[1]]$o
[1] "person, individual"

[[1]]$h[[1]]$h
[[1]]$h[[1]]$h[[1]]
[[1]]$h[[1]]$h[[1]]$o
[1] "organism, being"

[[1]]$h[[1]]$h[[1]]$h
[[1]]$h[[1]]$h[[1]]$h[[1]]
[[1]]$h[[1]]$h[[1]]$h[[1]]$o
[1] "living thing"

[[1]]$h[[1]]$h[[1]]$h[[1]]$h
[[1]]$h[[1]]$h[[1]]$h[[1]]$h[[1]]
[[1]]$h[[1]]$h[[1]]$h[[1]]$h[[1]]$o
[1] "unit"

[[1]]$h[[1]]$h[[1]]$h[[1]]$h[[1]]$h
[[1]]$h[[1]]$h[[1]]$h[[1]]$h[[1]]$h[[1]]
[[1]]$h[[1]]$h[[1]]$h[[1]]$h[[1]]$h[[1]]$o
[1] "object"

[[1]]$h[[1]]$h[[1]]$h[[1]]$h[[1]]$h[[1]]$h
[[1]]$h[[1]]$h[[1]]$h[[1]]$h[[1]]$h[[1]]$h[[1]]
[[1]]$h[[1]]$h[[1]]$h[[1]]$h[[1]]$h[[1]]$h[[1]]$o
[1] "physical entity"

[[1]]$h[[1]]$h[[2]]
[[1]]$h[[1]]$h[[2]]$o
[1] "causal agent"

[[1]]$h[[1]]$h[[2]]$h
[[1]]$h[[1]]$h[[2]]$h[[1]]
[[1]]$h[[1]]$h[[2]]$h[[1]]$o
[1] "physical entity"

[[1]]$h[[1]]$h[[2]]$h[[1]]$h
[[1]]$h[[1]]$h[[2]]$h[[1]]$h[[1]]
[[1]]$h[[1]]$h[[2]]$h[[1]]$h[[1]]$o
[1] "entity"

从此列表中手动创建:

list(structure(list(o = "preserver", h = list(structure(list(o = "person, individual", h = list(structure(list(o = "organism, being", h = list(structure(list(o = "living thing", h = list(structure(list(o = "unit", h = list(structure(list(o = "object", h = list(structure(list(o = "physical entity"), .Names = "o"))), .Names = c("o", "h")))), .Names = c("o", "h")))), .Names = c("o", "h")))), .Names = c("o", "h")), structure(list(o = "causal agent", h = list(structure(list(o = "physical entity", h = list(structure(list(o = "entity"), .Names = "o"))), .Names = c("o", "h")))), .Names = c("o", "h")))), .Names = c("o", "h")))), .Names = c("o", "h")))

关于解决方案:我在考虑Reduce,但我仍然无法找到解决方案。

另外,我想知道以其他方式表示这棵树的可能性(即不是通过这个巨大的嵌套列表;例如环境?)。

提前感谢您的帮助。

0 个答案:

没有答案