不用刻輪子喔。這裡簡單地把你的例子用 package data.tree 解析。
library(data.tree)
library(data.table)
library(magrittr)
dt <- fread('A B C D
a1 b1 NA NA
a2 b2 cx1 NA
a2 b2 cx1 dxx
a2 b2 cx2 NA
a3 b3 cx3 dx1
a3 b3 cx3 dx2
a4 b4 cx4 dx3')
# append a column to describe terminals
dt[, pathString := paste("theRoot", A, B, C, D, sep = "/")]
# convert data frame to a tree
dt.tree <- as.Node(dt)
dt.tree
# levelName
# 1 theRoot
# 2 |