title: R: merging matrices (not data.frames)
body: <p>merge is a very nice function: It merges matrices and data.frames, and returns a data.frame.</p>
  
  <blockquote>
    <p>Having rather big character matrices,
    is there another good way to merge -
    without data.frame conversion?</p>
  </blockquote>
  
  <hr>
  
  <p>Comment 1:
  A small function to merge a named vector with a matrix or data.frame. Elements of the vector can link to multiple entries in the matrix:</p>
  
  <pre><code>expand &lt;- function(v,m,by.m,v.name='v',...) {
    df &lt;- do.call(rbind,lapply(names(v),function(x) {
      pos &lt;- which(m[,by.m] %in% v[x])
      cbind(x,m[pos,],...)
    }))
    colnames(df)[1] &lt;- v.name
    df
  }
  </code></pre>
  
  <p>Example:</p>
  
  <pre><code>v &lt;- rep(letters,each=3)[seq_along(letters)]
  names(v) &lt;- letters
  m &lt;- data.frame(a=unique(v),b=seq_along(unique(v)),stringsAsFactors=F)
  expand(v,m,'a')
  </code></pre>