分配ID以在R中形成层次结构

时间:2018-08-02 07:30:59

标签: r

我为不同机构提供了大量数据。它们按层次结构中每个级别(级别1-5)的工作人员答复人数列出,级别1是代理商名称,级别5是最小的工作单位。我需要为层次结构中的每个响应分配ID号,例如,这样我就可以知道ID321是ID257下的分支,而ID257是代理商ID 110下的一个组。

有没有办法可以在R中做到这一点?

我想用它来形成每个代理商组织结构的树状图。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用data.tree形成代理商的树形结构:

# simulation of the group of agencies/companies data (5 levels)

df <- structure(list(var1 = c("Comp1", "Comp1", "Comp1", "Comp1", "Comp2", 
"Comp2", "Comp2", "Comp2", "Comp2"), var2 = c("Divis1", "Divis1", 
"Divis1", "Divis2", "Divis1a", "Divis1a", "Divis1a", "Divis1a", 
"Divis2a"), var3 = c("Dept1", "Dept1", "Dept1", "Dept1c", "Dept1a", 
"Dept1a", "Dept2a", "Dept2a", "Dept1b"), var4 = c("Sec1", "Sec2", 
"Sec2", "Sec3", "Sec1a", "Sec1a", "Sec2a", "Sec2a", "Sec3"), 
    var5 = c("A", "B", "C", "D", "E", "F", "G", "I", "J")), class = "data.frame", row.names = c(NA, 
9L))

#    var1    var2   var3  var4 var5
# 1 Comp1  Divis1  Dept1  Sec1    A
# 2 Comp1  Divis1  Dept1  Sec2    B
# 3 Comp1  Divis1  Dept1  Sec2    C
# 4 Comp1  Divis2 Dept1c  Sec3    D
# 5 Comp2 Divis1a Dept1a Sec1a    E
# 6 Comp2 Divis1a Dept1a Sec1a    F
# 7 Comp2 Divis1a Dept2a Sec2a    G
# 8 Comp2 Divis1a Dept2a Sec2a    I
# 9 Comp2 Divis2a Dept1b  Sec3    J

# convert dataframe into tree structure
df$owner <- "Owner"
df$pathString <- with (df, paste(owner, var1, var2, var3, var4, var5, 
                         sep = "/"))
df_n <- as.Node(df)
plot(df_n)

输出: Structure