Merge multiple data tables with duplicate column names

后端 未结 6 1407
感情败类
感情败类 2020-12-29 10:19

I am trying to merge (join) multiple data tables (obtained with fread from 5 csv files) to form a single data table. I get an error when I try to merge 5 data tables, but wo

6条回答
  •  离开以前
    2020-12-29 11:00

    Another way of doing this:

    dts <- list(DT1, DT2, DT3, DT4, DT5)
    
    names(dts) <- paste("y", seq_along(dts), sep="")
    data.table::dcast(rbindlist(dts, idcol="id"), x ~ id, value.var = "y")
    
    #   x y1 y2 y3 y4 y5
    #1: a 10 11 12 13 14
    #2: b 11 12 13 14 15
    #3: c 12 13 14 15 16
    #4: d 13 14 15 16 17
    #5: e 14 15 16 17 18
    #6: f 15 16 17 18 19
    

    The package name in "data.table::dcast" is added to ensure that the call returns a data table and not a data frame even if the "reshape2" package is loaded as well. Without mentioning the package name explicitly, the dcast function from the reshape2 package might be used which works on a data.frame and returns a data.frame instead of a data.table.

提交回复
热议问题