Joining tables based on different column names

后端 未结 3 1137
借酒劲吻你
借酒劲吻你 2021-01-20 23:28

I was watching a video[1] by Greg Reda about Pandas to see what Pandas can do how it compares with data.table. I was surprised to learn how difficult it was to join tables in d

3条回答
  •  被撕碎了的回忆
    2021-01-21 00:08

    Normally, when joining data.tables the column names don't actually matter. You just need to make sure both tables have a compatible key.

    library(data.table)
    dt1<-data.table(a=letters[1:10], b=1:10)
    setkey(dt1,a)
    dt2<-data.table(x=letters[1:10], y=10:1)
    setkey(dt2,x)
    
    dt1[dt2]
    

    Basically it will join on all the key columns. Normally you are joining on a key. If you really need to specify non-key columns, you can always cast the data.table to a data.frame and use the standard merge() function

    merge(as.data.frame(dt1),dt2, by.x="a", by.y="x")
    merge(as.data.frame(dt1),dt2, by.x="b", by.y="y")
    

提交回复
热议问题