R programming question: extract all the rows matching Ids
2
0
Entering edit mode
9.7 years ago
MAPK ★ 2.1k

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 • 16k views
ADD COMMENT
3
Entering edit mode
9.7 years ago
komal.rathi ★ 4.1k

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)])
ADD COMMENT
0
Entering edit mode

Thank you, but I want to use match function.

ADD REPLY
1
Entering edit mode

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

ADD REPLY
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

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.

ADD REPLY
0
Entering edit mode

@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

ADD REPLY
0
Entering edit mode

Thank you, Komal.

ADD REPLY
1
Entering edit mode
9.7 years ago
kangyueapril ▴ 80

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)])
ADD COMMENT

Login before adding your answer.

Traffic: 1998 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6