title: How can I summarise a factor or character variable?
body: <p>I would like to 'summarise' a factor variable in R, so that for each record I know what factor levels are present.</p>
  <p>Here is a simplified example dataframe:</p>
  <pre><code>df &lt;- data.frame(record= c(&quot;a&quot;,&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot;),
  species = c(&quot;COD&quot;, &quot;SCE&quot;, &quot;COD&quot;, &quot;COD&quot;,&quot;SCE&quot;,&quot;QSC&quot;))
  
  record species
       a     COD
       a     SCE
       b     COD
       c     COD
       c     SCE
       c     QSC
  </code></pre>
  <p>And this is what I am trying to achieve: <br></p>
  <pre><code>data.frame(record= c(a,b,c), species = c(&quot;COD, SCE&quot;, &quot;COD&quot;, &quot;COD, SCE, QSC&quot;))
  
      record       species
          a       COD, SCE
          b            COD
          c  COD, SCE, QSC
  </code></pre>
  <p>This is the closest I have been able to get, but it puts ALL levels of the factor with each record, rather than just the ones that should be present for each record.</p>
  <pre><code>summarise(group_by(df, record),
            species = (paste(levels(species), collapse=&quot;&quot;)))
  record   species
     &lt;fctr&gt;   &lt;chr&gt;
        a CODQSCSCE      &lt;- this should be CODSCE
        b CODQSCSCE      &lt;- this should just be COD
        c CODQSCSCE      &lt;- this is correct as CODQSCSCE as it has all levels
  </code></pre>
  <p><code>tapply</code> returns the same issue</p>
  <pre><code>tapply(df$species, df$record, function(x) paste(levels(x), collapse=&quot;&quot;))
     a           b           c 
  &quot;CODQSCSCE&quot; &quot;CODQSCSCE&quot; &quot;CODQSCSCE&quot; 
  </code></pre>
  <p>I need to find a way to tell which combinations of species factors are present for each record.</p>