[R] Need help with merge

analyst41 at hotmail.com analyst41 at hotmail.com
Thu Feb 10 03:16:30 CET 2011


Have

> actualsdf
   ID      Name datadate val
1  23 Acme Corp        1  23
2  23 Acme Corp        2  43
3  23 Acme Corp        3  54
4  23 Acme Corp        4  65
5  23 Acme Corp        5  23
6  23 Acme Corp        6  43
7  23 Acme Corp        7  NA
8  23 Acme Corp        8  43
9  23 Acme Corp        9  54
10 23 Acme Corp       10  32

> fcstdf
  fcstrundate fcstdate fcst ID      Name
1           5        6   22 23 Acme Corp
2           6        7   43 23 Acme Corp
3           7        8   54 23 Acme Corp
4           8        9   23 23 Acme Corp
5           9       10   NA 23 Acme Corp
6          10       11   13 23 Acme Corp

> mergeddf =merge(fcstdf,actualsdf,by.x = "fcstdate",by.y = "datadate",all =TRUE)

> mergeddf
   fcstdate fcstrundate fcst ID.x    Name.x ID.y    Name.y val
1         1          NA   NA   NA      <NA>   23 Acme Corp  23
2         2          NA   NA   NA      <NA>   23 Acme Corp  43
3         3          NA   NA   NA      <NA>   23 Acme Corp  54
4         4          NA   NA   NA      <NA>   23 Acme Corp  65
5         5          NA   NA   NA      <NA>   23 Acme Corp  23
6         6           5   22   23 Acme Corp   23 Acme Corp  43
7         7           6   43   23 Acme Corp   23 Acme Corp  NA
8         8           7   54   23 Acme Corp   23 Acme Corp  43
9         9           8   23   23 Acme Corp   23 Acme Corp  54
10       10           9   NA   23 Acme Corp   23 Acme Corp  32
11       11          10   13   23 Acme Corp   NA      <NA>  NA

I would like mergeddf to look like

> cleanmergeddf
   fcstdate fcstrundate fcst val ID      Name
1         1          NA   NA  23 23 Acme Corp
2         2          NA   NA  43 23 Acme Corp
3         3          NA   NA  54 23 Acme Corp
4         4          NA   NA  65 23 Acme Corp
5         5          NA   NA  23 23 Acme Corp
6         6           5   22  43 23 Acme Corp
7         7           6   43  NA 23 Acme Corp
8         8           7   54  43 23 Acme Corp
9         9           8   23  54 23 Acme Corp
10       10           9   NA  32 23 Acme Corp
11       11          10   13  NA 23 Acme Corp

I can think of an awkward way - but is there a direct merged command
that would produce the final output?

Thanks.



More information about the R-help mailing list