title: Merging heterogeneous data.frames
body: <p>I'm trying to merge two <code>data.frames</code> in R</p>
  
  <pre><code>d1 &lt;- data.frame(Id=1:3,Name=c("Yann","Anne","Sabri"),Age=c(21,19,31),Height=c(178,169,192),Grade=c(15,12,18))
  d2 &lt;- data.frame(Id=c(1,3,4),Name=c("Yann","Sabri","Jui"),Age=c(28,21,15),Sex=c("M","M","F"),City=c("Paris","Paris","Toulouse"))
  </code></pre>
  
  <p>I'd like to merge by <code>Id</code>, and retaining only <code>Id</code>, <code>Name</code>, <code>Age</code>, <code>Sex</code> and <code>Grade</code> columns in the final <code>data.frame</code>.</p>
  
  <p>I've come up with a lengthy code that does the job, but is there any better way?</p>
  
  <pre><code>dm &lt;- data.frame(Id=unique(c(d1$Id,d2$Id)))
  dm.d1.rows &lt;- sapply(dm$Id, match, table = d1$Id)
  dm.d2.rows &lt;- sapply(dm$Id, match, table = d2$Id)
  for(i in c("Name", "Age","Sex","Grade")) {
      if(i %in% colnames(d1) &amp;&amp; is.factor(d1[[i]]) || i %in% colnames(d2) &amp;&amp; is.factor(d2[[i]])) dm[[i]]&lt;- factor(rep(NA,nrow(dm)),
              levels=unique(c(levels(d1[[i]]),levels(d2[[i]]))))
      else dm[[i]]&lt;- rep(NA,nrow(dm))
      if(i %in% colnames(d1)) dm[[i]][!is.na(dm.d1.rows)] &lt;- d1[[i]][na.exclude(dm.d1.rows)]
      if(i %in% colnames(d2)) dm[[i]][!is.na(dm.d2.rows)] &lt;- d2[[i]][na.exclude(dm.d2.rows)]
  }
  </code></pre>