【问题标题】:Tree-Structure to wide Table in RR中的树结构到宽表
【发布时间】:2021-09-24 12:39:51
【问题描述】:

如何转换树结构数据框

到这样的宽表?

【问题讨论】:

    标签: r dataframe transform


    【解决方案1】:
    library(data.tree)
    

    直接使用名称而不是 data.tree 中的 ID 更容易,因此我们进行自连接以在同一个表中获取父名称。

    df <- merge(df, df, by.x = "ParentId", by.y = "Id",
                suffixes = c("", ".Parent"))
    
    
    tree <- FromDataFrameNetwork(df[c("Name.Parent", "Name")])
    
    #                 levelName
    # 1  Biota                 
    # 2   ¦--Plantea           
    # 3   ¦   ¦--Tree          
    # 4   ¦   ¦   ¦--Bonsai    
    # 5   ¦   ¦   °--Apple-Tree
    # 6   ¦   °--Flower        
    # 7   °--Animal            
    # 8       ¦--Bear          
    # 9       ¦--Fish          
    # 10      °--Bird 
    
    ToDataFrameTypeCol(tree)
    
    #   level_1 level_2 level_3    level_4
    # 1   Biota Plantea    Tree     Bonsai
    # 2   Biota Plantea    Tree Apple-Tree
    # 3   Biota Plantea  Flower       <NA>
    # 4   Biota  Animal    Bear       <NA>
    # 5   Biota  Animal    Fish       <NA>
    # 6   Biota  Animal    Bird       <NA>
    

    有数据:

    df <- tibble::tribble(
      ~Id, ~Name, ~ParentId,
      1, "Biota", NA,
      2, "Plantea", 1,
      3, "Animal", 1,
      4, "Tree", 2,
      5, "Flower", 2,
      6, "Bear", 3,
      7, "Fish", 3,
      8, "Bird", 3,
      9, "Bonsai", 4,
      10, "Apple-Tree", 4,
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      相关资源
      最近更新 更多