Merge multiple data tables with duplicate column names

后端 未结 6 1409
感情败类
感情败类 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 10:47

    Alternatively you could setNames for the columns before and do merge like this

    dts = list(DT1, DT2, DT3, DT4, DT5)
    names(dts) = paste('DT', c(1:5), sep = '')    
    
    dtlist = lapply(names(dts),function(i) 
             setNames(dts[[i]], c('x', paste('y',i,sep = '.'))))
    
    Reduce(function(...) merge(..., all = T), dtlist)
    
    #   x y.DT1 y.DT2 y.DT3 y.DT4 y.DT5
    #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
    

提交回复
热议问题