我如何总结一个因素或字符变量?

How can I summarise a factor or character variable?

我想 'summarise' R 中的一个因子变量,这样对于每条记录我都知道存在哪些因子水平。

这是一个简化的示例数据框:

df <- data.frame(record= c("a","a","b","c","c","c"),
species = c("COD", "SCE", "COD", "COD","SCE","QSC"))

record species
     a     COD
     a     SCE
     b     COD
     c     COD
     c     SCE
     c     QSC

这就是我想要实现的目标:

data.frame(record= c(a,b,c), species = c("COD, SCE", "COD", "COD, SCE, QSC"))

    record       species
        a       COD, SCE
        b            COD
        c  COD, SCE, QSC

这是我能得到的最接近的值,但它将所有水平的因素放在每条记录中,而不仅仅是每条记录应该出现的水平。

summarise(group_by(df, record),
          species = (paste(levels(species), collapse="")))
record   species
   <fctr>   <chr>
      a CODQSCSCE      <- this should be CODSCE
      b CODQSCSCE      <- this should just be COD
      c CODQSCSCE      <- this is correct as CODQSCSCE as it has all levels

tapplyreturns同样的问题

tapply(df$species, df$record, function(x) paste(levels(x), collapse=""))
   a           b           c 
"CODQSCSCE" "CODQSCSCE" "CODQSCSCE" 

我需要找到一种方法来判断每条记录存在哪些物种因素组合。

使用unique():

library(dplyr)
df %>% 
    group_by(site) %>% 
    summarise(species = paste(unique(species), collapse = ', '))


# A tibble: 3 x 2
    site       species
  <fctr>         <chr>
1      a      COD, SCE
2      b           COD
3      c COD, SCE, QSC