在数据框的注释中搜索关键字

Searching for keywords in the comments of a data frame

我有这个数据集,我正在检查它以确认每只动物的 ID 多年来是否正确。为此,我使用以下代码在 Excel 文件的注释中搜索关键字:

    do.call(rbind,breeder[-1]) %>%   
                select(Year, `Old Tag`, Tag_11, PIT, Sex  Orig, Group,Comments) %>% 
filter(Sex != "m",grepl(keywords, Comments)) %>%   
        arrange(., desc(PIT)) %>%   
        print.data.frame

这里是关键词:

keywords <- c('retag','lost','Was', 'was','original','change','CHANGE','check','CHECK','switched','temp only','should',
              'had tag','new','give','GIVE', 'given','^--', 'tag', 'TAG', 'tags', 'tagged', 'temp', 'Temporarily', 
              'Temporary', 'Released', 'removed', 'Processing', 'processing', 'Processed', 'previously', 'pit', 'pits', 
              'PIT', 'orig', 'original', 'old', 'OLD', 'new', 'New', 'not', 'listed', 'last', 'had', 
              'could', 'Chech', 'assigned')

然而,当我 运行 代码时,R 只使用第一个词 - 'retag',我得到这个输出:

  Year Old Tag Tag_11              PIT Sex Orig Group                       Comments
1 2015    <NA>    367 <NA>   f c   o Temporary tag -  retag as #3
2 2016    <NA>    367 <NA>   f c   o Temporary tag -  retag as #3
Warning message:
In grepl(keywords, Comments) :
  argument 'pattern' has length > 1 and only the first element will be used

我需要搜索数据框中所有关键词的评论,如何搜索多个词?

更新:当我使用下面的代码时,所有的参数都没有在输出中被识别。我究竟做错了什么?例如,'Released' 未被读取。

 deadKeywords <- c('died', 'Released', 'processed', 'Processed', 'processing', 'Processing', 'process', 'dead', 'Dead', 'Died') %>% paste0(., collapse = " | ")

 commentSearch <- do.call(rbind,breeder[-1]) %>% 
select(Year, Old Tag, Tag_11, PIT, Sex, Orig, Group, Comments) %>% 
filter(grepl(deadKeywords, Comments)) %>% arrange(., desc(PIT)) %>% 
print.data.frame

grepl 函数在其模式中未向量化。为了使模式参数在匹配字符向量中的任何项目的意义上成为 "vectorized" ,您需要将它们与正则表达式“|”-运算符绑定在一起,以便 grepl 的模式参数应该是:

 paste0( keywords, collapse="|")

另一种使用方法(如果关键字是一个很长的向量可能有用):

any( sapply( keywords, grepl, x=Comments) )