我有两个数据帧,df1
和df2
用相同的列标题
x <- c(1,2,3)
y <- c(3,2,1)
z <- c(3,2,1)
names <- c("id","val1","val2")
df1 <- data.frame(x, y, z)
names(df1) <- names
a <- c(1, 2, 3)
b <- c(1, 2, 3)
c <- c(3, 2, 1)
df2 <- data.frame(a, b, c)
names(df2) <- names
和AM执行合并
#library(dplyr) # not needed for merge
joined_df <- merge(x=df1, y=df2, c("id"),all=TRUE)
这给我joined_df
中的列为id, val1.x, val2.x, val1.y, val2.y
问题
有没有办法共同找到了在原始数据帧相同的标题,给所加入的数据帧id, val1.x, val1.y, val2.x, val2.y
列顺序列?
请注意,在我的实际数据框中,我有115列,所以如果可能的话,我想避免使用joned_df <- joined_df[, c(1, 2, 4, 3, 5)]
。
更新/编辑:另外,我想维护列标题的原始顺序,所以按字母顺序排序不是一个选项(在我的实际数据中,我意识到它可以与我给出的示例一起使用)。
我期望的输出是
id val1.x val1.y val2.x val2.y
1 1 3 1 3 3
2 2 2 2 2 2
3 3 1 3 1 1
更新与解决方案,一般情况下
接受的答案解决了我的问题很好。 我在这里稍微修改了代码以使用原始列名称,而不必在rep
函数中对它们进行硬编码。
#specify columns used in merge
merge_cols <- c("id")
# identify duplicate columns and remove those used in the 'merge'
dup_cols <- names(df1)
dup_cols <- dup_cols [! dup_cols %in% merge_cols]
# replicate each duplicate column name and append an 'x' and 'y'
dup_cols <- rep(dup_cols, each=2)
var <- c("x", "y")
newnames <- paste(dup_cols, ".", var, sep = "")
#create new column names and sort the joined df by those names
newnames <- c(merge_cols, newnames)
joined_df <- joined_df[newnames]
的数据帧'dplyr'负载是多余的。 'merge'函数在'base'中。可以使用'joined_df [c('id','val1.x','val2.x','val1.y','val2.y')]' –
,我用它来做其他事情,并且意外地复制它。 – tospig