Extending Suffixes in Merge to All Non-by Columns

前端 未结 3 1830
后悔当初
后悔当初 2021-01-04 12:06

suffixes in merge works only on common column names. Is there anyway to extend this to the rest of the columns as well without manually updating co

3条回答
  •  清酒与你
    2021-01-04 12:29

    This is an interesting question, and I doubt that extending merge would be a straightforward solution unless Matt Dowle and Co. think it's something worth implementing in merge.data.table.

    Here's one approach that came to mind:

    DTs <- c("df1", "df2")
    suffixes <- seq_along(DTs)
    
    for (i in seq_along(DTs)) {
      Name <- setdiff(colnames(get(DTs[i])), "a")
      setnames(get(DTs[i]), Name, paste(Name, suffixes[i], sep = "."))
    }
    
    merge(df1, df2, by = "a") # Will obviously work as you expect now
    

提交回复
热议问题