本文介绍了将合并后缀扩展到所有非按列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
suffixes
仅适用于通用列名.无论如何,是否可以将其扩展到其余的列,而无需在合并之前手动更新列?
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 columns before the merge?
就是-
df1 <- data.table(
a = c(1,2,3,4,5,6),
b = c('a','b','f','e','r','h'),
d = c('q','l','o','n','q','z')
)
df2 <- data.table(
a = c(1,2,3,4,5,6),
d = c('q','l','o','n','q','z')
)
colnames(merge(df1,df2, by = 'a', suffixes = c("1","2")))
#[1] "a" "b" "d1" "d2" what it does
#[1] "a" "b1" "d1" "d2" what I'd like it to do
我当前处理此问题的方式类似于@mrip的答案.
The current way I'm handling this resembles @mrip's answer.
df1 <- data.table(
a = c(1,2,3,4,5,6),
b = c('a','b','f','e','r','h'),
r = c('a','b','f','e','r','h'),
d = c('q','l','o','n','q','z')
)
df2 <- data.table(
a = c(1,2,3,4,5,6),
c = c('a','b','f','e','r','h'),
q = c('a','b','f','e','r','h'),
d = c('q','l','o','n','q','z')
)
dfmerge <- (merge(df1,df2, by = c("a"), suffixes = c("1","2")))
setnames(
dfmerge,
setdiff(names(df1),names(df2)),
paste0(setdiff(names(df1),names(df2)),"1")
)
setnames(
dfmerge,
setdiff(names(df2),names(df1)),
paste0(setdiff(names(df2),names(df1)),"2")
)
colnames(dfmerge)
#[1] "a" "b1" "r1" "d1" "c2" "q2" "d2"
推荐答案
一个简单的解决方案:
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"
感谢里卡多·萨波特塔(Ricardo Saporta)的评论,此注释大为清除了该错误并教给我一些新的提示!
thanks to comments by Ricardo Saporta for cleaning this up considerably and teaching me a few new tips!
这篇关于将合并后缀扩展到所有非按列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!