title: Compute mean pairwise covariance between elements in a list
body: <p>I have the following data frames:</p>
  
  <pre><code># df1
  id   cg_v
  1       a
  2       b
  3     a b
  4     b c
  5   b c d
  6       d
  
  # df2
  id  cg
  1    a
  2    b
  3    a
  3    b
  4    b
  4    c
  5    b
  5    c
  5    d
  6    d
  </code></pre>
  
  <p>I need to add a column to <code>df1</code> that contains the mean covariance computed across each pair of elements in <code>cg_v</code>. If <code>cg_v</code> contains only one element, then I would like the new column to contain its variance.</p>
  
  <p>I can get a covariance matrix by <code>cov(crossprod(table(df2)))</code></p>
  
  <pre><code>#          a         b          c          d
  a  0.9166667 0.0000000 -0.5833333 -0.6666667
  b  0.0000000 2.0000000  1.0000000  0.0000000
  c -0.5833333 1.0000000  0.9166667  0.3333333
  d -0.6666667 0.0000000  0.3333333  0.6666667
  </code></pre>
  
  <p>What do I do from here?</p>
  
  <p>The end result should be like this:</p>
  
  <pre><code># df1
  id   cg_v      cg_cov
  1       a   0.9166667
  2       b   2.0000000
  3     a b   0.0000000
  4     b c   1.0000000
  5   b c d   0.4444444  # This is equal to (1.0000000 + 0.3333337 + 0.0000000)/3
  6       d   0.6666667
  </code></pre>
  
  <p>Code to generate <code>df1</code> and <code>df2</code>:</p>
  
  <pre><code>df1 &lt;- structure(list(id = c(1L, 2L, 3L, 4L, 5L, 6L),
                        cg_v = c("a", "b", "a b", "b c", "b c d", "d")),
                   .Names = c("id", "cg_v"),
                   class = "data.frame", row.names = c(NA, -6L))
  
  df2 &lt;- structure(list(id = c(1L, 2L, 3L, 3L, 4L, 4L, 5L, 5L, 5L, 6L),
                        cg = c("a", "b", "a", "b", "b", "c", "b", "c", "d", "d")),
                   .Names = c("id", "cg"),
                   class = "data.frame", row.names = c(NA, -10L))
  </code></pre>