[R] help to merge two data frame if name matches

Marianne Promberger marianne.promberger at kcl.ac.uk
Tue Nov 9 16:41:14 CET 2010


Hi Mohan,

Mohan L <l.mohanphysics at gmail.com> 09-Nov-10 15:17:
 
> I want to merge ip,bsent,breceived column to "main" , If the name in
> the the "main" data frame is there in the "other" data frame . some
> thinng like this:
> 
> name    id  memory   storage  ip       bsent     breceived
> 
> mohan    1    100      20         1         12.00     0.01
> ram        1    200      100        0         00.00    0.00
> kumar    1    400      50          1         1.00      1.00
> xxx        1    100      40          1         00.00    1.110
> aaa         1    800      45         0	       00.00    00.00
> mount    1    200      80          0         00.00    00.00
> 
> 
> If in case the name in the "main" data frame does not there in the
> "other" data frame, simple I want to add zero to ip,bsent,breceived
> value.

Is this what you want?

newdat <- merge(main,other,by="name",all.x=T)

   name id memory storage ip bsent breceived
1   aaa  1  800.0    45.0 NA    NA        NA
2 kumar  1  400.0    50.0 NA    NA        NA
3 mohan  1  100.2     1.1  1    12      0.01
4 mount  1  200.0    80.0 NA    NA        NA
5   ram  1  200.0   100.0 NA    NA        NA
6   xxx  1  100.0    40.0  1     0      1.11

newdat[is.na(newdat)] <- 0

newdat

   name id memory storage ip bsent breceived
1   aaa  1  800.0    45.0  0     0      0.00
2 kumar  1  400.0    50.0  0     0      0.00
3 mohan  1  100.2     1.1  1    12      0.01
4 mount  1  200.0    80.0  0     0      0.00
5   ram  1  200.0   100.0  0     0      0.00
6   xxx  1  100.0    40.0  1     0      1.11

Marianne

-- 
Marianne Promberger PhD, King's College London
http://promberger.info
R version 2.12.0 (2010-10-15)
Ubuntu 9.04



More information about the R-help mailing list