Skip to content

merging issue.........

5 messages · Pete B, Adrian Dusa, Heinz Tuechler +1 more

#
hi, I have a question about merging two files.
For example, I have two files, the first file is like the following:

id   trait1
1    10.2
2    11.1
3    9.7
6    10.2
7    8.9
10  9.7
11  10.2

The second file is like the following:
id    trait2
1     9.8
2     10.8
4     7.8
5     9.8
6     10.1
12    10.2
13    10.1

now I want to merge the two files by the variable "id", I only want to keep
the "id"s which show up in the first file. Even the "id" does not show up in
the second file, it doesn't matter, I can keep the missing values. So my
question is: how can I merge the two files and keep only the rows whose "id"
show up in the first file?
I know how to do it is SAS, just use the following code: 
merge data1(in=in1) data2(in=in2);
by id;
if in1;

but I really have no idea about how to do it in R.

thank you in advance,

karean
#
Try the merge function
?merge

in1 = "id trait1 
1    10.2 
2    11.1 
3    9.7 
6    10.2 
7    8.9 
10  9.7 
11  10.2 
"

in2 = "id trait2 
1     9.8 
2     10.8 
4     7.8 
5     9.8 
6     10.1 
12    10.2 
13    10.1
" 

data1 = read.table(textConnection(in1), header=T)
data2 = read.table(textConnection(in2), header=T)

mymerge = merge(data1,data2,all.x=TRUE)
print(mymerge)
karena wrote:

  
    
#
Hi Karean,

If your first object is called obj1 and the second called obj2, then:
id trait1 trait2
1  1   10.2    9.8
2  2   11.1   10.8
3  3    9.7     NA
4  6   10.2   10.1
5  7    8.9     NA
6 10    9.7     NA
7 11   10.2     NA

Hope this helps,
Adrian
On Wednesday 13 January 2010, karena wrote:

  
    
#
Did you consider to look at the help page for merge?
h
At 22:01 13.01.2010, karena wrote: