I have two data frames. df1 and df2. df1 has three columns a, b, and c. df2 has three columns x, y, and z. I would like to merge df1 and df2 and the condition is if a==x OR b==y. If any one of the conditions is true, it should merge.
Merging two data frames using 'OR' i.e., condition should be if any of the column matches then merge
Asked
Active
Viewed 40 times
0
-
It would be easier to help if you create a small reproducible example (for df1 and df2) along with your expected output. So everyone can test their ideas and see which one might be an answer. Here are some information about reproducible examples: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – tamtam Mar 05 '21 at 06:33
1 Answers
0
This will merge df1 and df2 only if the columns a and x are the same, or b and y, keeping the column name of df1. It will do nothing if neither of the columns are the same or if both are the same.
df1=data.frame(a=1:3, b=4:6, c=7:9)
df2=data.frame(x=9:11, y=4:6, z=8:10)
library(dplyr)
df3=data.frame()
library(dplyr)
bindem=FALSE
if (identical(df1$a, df2$x) & identical(df1$b, df2$y)) {
} else if (identical(df1$a, df2$x)) {
df2=select(df2, -x)
bindem=TRUE
} else if (identical(df1$b, df2$y)) {
df2=select(df2, -y)
bindem=TRUE
}
if (bindem) {
df3=cbind(df1, df2)
}
a b c x z
1 1 4 7 9 8
2 2 5 8 10 9
3 3 6 9 11 10

Vons
- 3,277
- 2
- 16
- 19