ben890
ben890

Reputation: 1133

Is it possible to use column indices in merge?

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)

Upvotes: 6

Views: 9588

Answers (1)

vpipkt
vpipkt

Reputation: 1707

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...

Upvotes: 10

Related Questions