title: mapply within ddply
body: <p>note: this is a direct follow up to this <a href="https://stackoverflow.com/questions/8749589/create-a-scoring-matrix-from-two-dataframes">previous question</a></p>
  
  <hr>
  
  <p>I have very long dataframe consisting of two columns that I am using as arguments for a function that will find the value of a third column using mapply as so:</p>
  
  <pre><code>df$3rd &lt;- mapply(myfunction, A=df$1st, B=df$2nd)
  </code></pre>
  
  <p>where <code>myfunction</code> has arguments A and B. While this works great for small datasets, it stalls for large datasets so I was thinking a good way to approach the problem would be to apply this function using <code>ddply</code>. I don't know if <code>ddply</code> is the best approach for this problem but I am also having some trouble with syntax. So suggestions for either would be appreciated.</p>
  
  <p>This is what I am trying:</p>
  
  <pre><code>&gt; df$3rd &lt;- ddply(df, .(1st), function(x) x$3rd &lt;-
  &gt; mapply(myfunction, A=x$1st, B=df$second))
  </code></pre>
  
  <p>and this is the error I am getting:</p>
  
  <pre><code>Error in `$&lt;-.data.frame`(`*tmp*`, "n", value = c(1L, 1L, 1L, 1L, 1L,  : 
    replacement has 112 rows, data has 16
  </code></pre>
  
  <p>EDIT:</p>
  
  <hr>
  
  <hr>
  
  <p>In light of the answer and comments I I am posting a small reproducible example below - it is one of the answers from the previous question. However as the commenters below note, ddply is probably not the way to go. I am trying Ramnath's solution right now.</p>
  
  <pre><code>library(reshape2)
  foo &lt;- data.frame(x = c('a', 'a', 'a', 'b', 'b', 'b'), 
                    y = c('ab', 'ac', 'ad', 'ae', 'fx', 'fy'))
  bar &lt;- data.frame(x = c('c', 'c', 'c', 'd', 'd', 'd'), 
                    y = c('ab', 'xy', 'xz', 'xy', 'fx', 'xz'))
  
  nShared &lt;- function(A, B) {
      length(intersect(with(foo, y[x==A]), with(bar, y[x==B])))
  }
  
  # Enumerate all combinations of groups in foo and bar
  (combos &lt;- expand.grid(foo.x=unique(foo$x), bar.x=unique(bar$x)))
  
  # Find number of elements in common among all pairs of groups
  combos$n &lt;- mapply(nShared, A=combos$foo.x, B=combos$bar.x)
  
  # Reshape results into matrix form
  dcast(combos, foo.x ~ bar.x)
  #   foo.x c d
  # 1     a 1 0
  # 2     b 0 1
  </code></pre>