Merge multiple data tables with duplicate column names

后端 未结 6 1411
感情败类
感情败类 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:51

    Here's a way of keeping a counter within Reduce, if you want to rename during the merge:

    Reduce((function() {counter = 0
                        function(x, y) {
                          counter <<- counter + 1
                          d = merge(x, y, all = T, by = 'x')
                          setnames(d, c(head(names(d), -1), paste0('y.', counter)))
                        }})(), list(DT1, DT2, DT3, DT4, DT5))
    #   x y.x y.1 y.2 y.3 y.4
    #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
    

提交回复
热议问题