Data.table - left outer join on multiple tables

后端 未结 2 534
时光取名叫无心
时光取名叫无心 2020-12-10 08:18

Suppose you have data like

fruits <- data.table(FruitID=c(1,2,3), Fruit=c(\"Apple\", \"Banana\", \"Strawberry\"))
colors <- data.table(ColorID=c(1,2,3,         


        
2条回答
  •  伪装坚强ぢ
    2020-12-10 08:28

    I just committed a new feature in data.table, v1.9.5, with which we can join without setting keys (that is, specify the columns to join by directly, without having to use setkey() first):

    With that, this is simply:

    require(data.table) # v1.9.5+
    fruits[tastes, on="FruitID"][colors, on="FruitID"] # no setkey required
    #    FruitID      Fruit TasteID  Taste ColorID  Color
    # 1:       1      Apple       1 Sweeet       1    Red
    # 2:       1      Apple       2   Sour       1    Red
    # 3:       1      Apple       1 Sweeet       2 Yellow
    # 4:       1      Apple       2   Sour       2 Yellow
    # 5:       1      Apple       1 Sweeet       3  Green
    # 6:       1      Apple       2   Sour       3  Green
    # 7:       2         NA      NA     NA       4 Yellow
    # 8:       3 Strawberry       3  Sweet       5    Red
    

提交回复
热议问题