Extending Suffixes in Merge to All Non-by Columns

前端 未结 3 1973
后悔当初
后悔当初 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条回答
  •  旧时难觅i
    2021-01-04 12:33

    A simple solution:

    mrg<-(merge(df1,df2, by = 'a', suffixes = c("1","2")))
    setnames(mrg,paste0(names(mrg),ifelse(names(mrg) %in% setdiff(names(df1),names(df2)),"1","")))
    setnames(mrg,paste0(names(mrg),ifelse(names(mrg) %in% setdiff(names(df2),names(df1)),"2","")))
    
    > names(mrg)
    [1] "a"  "b1" "d1" "d2"
    

    Edit: thanks to comments by Ricardo Saporta for cleaning this up considerably and teaching me a few new tips!

提交回复
热议问题