将多个值加入同一个单元格 R

Join multiple values into same cell R

我有一个数据框,其中每个文档的 pos 值都拆分为单个标记。如何将各个 pos 值合并到一个由逗号分隔的单元格中? 所以现在我有类似

的东西
  doc_id sentence_id token_id    token  pos entity
1  text1           1        1   xxxxxx PRON       
2  text1           1        2     xxxx  AUX       
3  text1           1        3      xxx  AUX       
4  text1           1        4  xxxxxxx VERB       
5  text2           1        5     xxxx  DET       
6  text2           1        6      xxx NOUN  

我怎样才能把它变成

  doc_id                      pos    entity
1  text1  PRON, AUX, AUX, VERB...       
2  text2  AUX, NOUN, PRON, ADJ...       
3  text3  ...
4  text4  ...  
5  text5  ...
6  text6  ...

我是否需要创建一个新的数据框,或者是否有可以直接执行此操作的 Spacy 函数? 谢谢

你可以这样折叠它:

aggregate(pos ~ doc_id, doc_df, paste, collapse = ", ")

您可以将它存储在一个单独的数据框中,并合并到您想要从原始数据中包含的任何其他列,或者如果您只需要这两列,那么您可以直接使用它。

我们可以使用 dplyr

library(dplyr)     
df1 %>%
     group_by(doc_id, entity) %>%
     summarise(pos = toString(pos), .groups = 'drop')