This is a test version of Biostars. For the public version, visit https://www.biostars.org.
R programming question: extract all the rows matching Ids

Hi Everyone,

I want to extract all the matching rows using ids in the sample column. I have these two data frames and using the sample IDs in df1, I want to look into df2 Sample column and extract all the matching rows from df2 and append to df1. I would specifically like to use R and would like to use match and cbind functions for this. Thank you your help.

df1

Sample     MPK     ET     TRN
ATF        44      55     5
CBD        49      22     66
GGY        50      4      77

df2

Project     Sample     Target      
PL-gen      ATF        3435      
TT-gen      TT         22333      
HY-gen      GGY        43333

Result:

Sample    MPK    ET    TRN    Project    Target
ATF       44     55    5      PL-gen     3435
CBD       49     22    66     NA         NA
GGY       50     4     77     HY-Gen     43333
cbind dataframe match

2 answers

See merge for how to do a left, right and outer join.

result <- merge(df1, df2, by="Sample")

Update : using cbind & match:

result <- cbind(df1, df2[match(df2$Sample, df1$Sample),c(1,3)])

Thank you, but I want to use match function.

Is it a homework question which specifically asks you to use match & cbind?!

No, it is something I need to do for my research and I will be using match and cbind functions primarily for the project. I need to learn how to use match function specifically.

@MAPK if you want to learn how to work with a specific function in R, you can simply do for instance ?match or help(match) or even you can see the examples given by a specific package by just writing example(match). The easiest way is to use google for this . for example you can find so many information about a specific function. The best is to first look at them and then try to program and then if you face problem post the exact problem. this way you can learn how to do it yourself otherwise you will always look for a help https://stat.ethz.ch/R-manual/R-patched/library/base/html/match.html

Thank you, Komal.

x %in% table is just same as match(x,table,nomatch = 0)

You can use R code as:

> com_id <- intersect(df1$Sample,df2$Sample)
> result <- cbind(df1[df1$Sample %in% com_id,],df2$Sample[df2$Sample %in% com_id, c(1,3)])

Log in to answer this question.