6

If I have two dataframes that I wish to merge, is there a way to merge by the column index rather than the name of the column?

For instance if I have these two dfs, and want to merge on x.x1 and y.x2.

dtest <- data.frame(x1 = 1:10, y = 2:11)
dtest2 <- data.frame(x2 = 1:10, y1 = 11:20)

I've tried the following but I can't get it to work

xy <- merge(dtest, dtest2, by.x = x[,1], by.y = y[,1], all.x = TRUE, all.y = TRUE)
2
  • if there's a better function to use than merge for this use case, I'd love to hear about it.
    – ben890
    Jan 23, 2015 at 19:15
  • Please include the desired result Jan 23, 2015 at 19:18

1 Answer 1

10

Here you go:

xy <- merge(dtest, dtest2, by.x = 1, by.y = 1, all.x = TRUE, all.y = TRUE)

From help(merge): Columns to merge on can be specified by name, number or by a logical vector...

1
  • Actually vpipkt is it possible to use the join function in the plyr function? Also could I join using two columns in each dataframe? something like the following: xy <- join(df1, df2, by = c(1,2), type = "inner")
    – ben890
    Jan 30, 2015 at 22:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.