-2

I need to merge two csv structured as follow:

csv1 =

1.1, 1, 2, 3, 4, 5, 6 
1.2, 1, 2, 3, 4, 5, 6 
1.3, 1, 2, 3, 4, 5, 6 

csv2 =

1.1, a, b, c, d, e, f 
1.2, a, b, c, d, e, f 
1.3, a, b, c, d, e, f 

both csv have the first column as "ID" (1.1, 1.2, 1.3).

So what I need is a third csv structured whit same rows number, using ID column as merging point:
csv merged =

1.1, 1, 2, 3, 4, 5, 6, a, b, c, d, e, f 
1.2, 1, 2, 3, 4, 5, 6, a, b, c, d, e, f 
1.3, 1, 2, 3, 4, 5, 6, a, b, c, d, e, f 


I tried to use function merge but I didn't get the expected result.
I used the following code:

> dt1 <- read.csv(test, header = FALSE)<br>
> dt1<br>
   V1 V2 V3 V4 V5 V6 V7<br>
1 1.1  1  2  3  4  5  6<br>
2 1.2  1  2  3  4  5  6<br>
3 1.3  1  2  3  4  5  6<br>
> dt2 <- read.csv(test2, header = FALSE)<br>
> dt2<br>
   V1 V2 V3 V4 V5 V6  V7<br>
1 1.1  a  b  c  d  e  f <br>
2 1.2  a  b  c  d  e  f <br>
3 1.3  a  b  c  d  e  f <br>
> merge(dt1, dt2)<br>
[1] V1 V2 V3 V4 V5 V6 V7<br>
<0 rows> (or 0-length row.names)<br><br>

Thanks for attention.

smci
  • 32,567
  • 20
  • 113
  • 146
  • 1
    When `by=` is not specified merge will use all columns to merge, hence no match. Try `merge(dt1, dt2, by = "V1")` and it should work. – zx8754 Jan 11 '18 at 11:51

1 Answers1

0

One way to do it would be:

merge(dt1, dt2, by.x = 'V1', by.y = 'V1')

Another way would be:

dt1$v11 <- dt2[match(dt1$V1, dt2$V1), 2]
dt1$v12 <- dt2[match(dt1$V1, dt2$V1), 3]
dt1$v13 <- dt2[match(dt1$V1, dt2$V1), 4]
dt1$v14 <- dt2[match(dt1$V1, dt2$V1), 5]
dt1$v15 <- dt2[match(dt1$V1, dt2$V1), 6]
dt1$v16 <- dt2[match(dt1$V1, dt2$V1), 7]

This is also a duplicate question for which answers can be found here:

How to join (merge) data frames (inner, outer, left, right)?

Matching values in columns in R

Ankur Sinha
  • 6,473
  • 7
  • 42
  • 73