I have a data frame (named as df) with single column of protein IDs and other file with two columns of protein IDs (named as df1). I need to find the df IDs present in either first or second column of df1 and extract corresponding Id from the df1.

df = data.frame(p = c("ENSG00000198400","ENSG00000066044","ENSG00000188612","ENSG00000177606","ENSG00000146648"))
df1 = data.frame(p1 = c("ENSG00000105647","ENSG00000110395","ENSG00000165119","ENSG00000160293","ENSG00000198400","ENSG00000198400"),p2 = c("ENSG00000198400","ENSG00000198400","ENSG00000198400","ENSG00000142949","ENSG00000112936","ENSG00000162434"))

Sample output:

df2= data.frame(p = c("ENSG00000198400","ENSG00000198400","ENSG00000198400","ENSG00000198400","ENSG00000198400"),p2 = c("ENSG00000105647","ENSG00000110395","ENSG00000165119","ENSG00000112936","ENSG00000162434"))
  • $\begingroup$ This seems to be an XY problem. Can you give us an idea of your bigger picture problem? $\endgroup$
    – Ram RS
    Oct 17, 2022 at 20:29
  • 1
    $\begingroup$ I'd say this belongs on Stack Overflow as is more of a pure coding problem - and you'll get a faster response there. I'd suggest deleting this and reposting here. $\endgroup$
    – user438383
    Oct 17, 2022 at 20:51
  • $\begingroup$ Gene names... looks like there's a biology aspect to this; adding more context to the question would make it more obviously bioinformatics. $\endgroup$
    – gringer
    Oct 18, 2022 at 20:33

1 Answer 1


you can try this:

df = data.frame(p = c("ENSG00000198400","ENSG00000066044","ENSG00000188612",
df1 = data.frame(p1 = c("ENSG00000105647","ENSG00000110395","ENSG00000165119",
                 p2 = c("ENSG00000198400","ENSG00000198400","ENSG00000198400",

df2 = rbind(df1[df1$p1 %in% df$p,],df1[df1$p2 %in% df$p,])

df2 <- transform(df2, p2 = ifelse(df2$p2%in%df$p, p1, p2), p1 = ifelse(df2$p2%in%df$p, p2, p1))

Your Answer

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

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