greplpattern,df中的错误:正则表达式无效

问题描述

我一直在尝试在列中搜索特定模式。 我的模式是一个很大的单词列表(> 2000),要显示的列有数百万行(df $ column1)

我已经使用其他数据框中的列创建了模式

word<-df2$words_to_use
pattern<-paste0('.*',word,'.*',collapse ='|')

所以我的模式看起来像(> 2000个单词):

.* word1.* | .* word2.* | .* word3.* | .* word4.* 

我想在df中创建一个Y / N列,该列说明df $ column1是否包含模式中的任何单词。

做到这一点

df$check<-ifelse(grepl(pattern,df$column1),'Y','N')

对于小模式它很好用,但对于大模式,我会收到错误消息

Error in grepl(pattern,df$column1):invalid regular expression

非常感谢您能帮助我!

解决方法

如果元素很多,请不要使用pastelapply遍历模式向量,而不是Reduce一起

ifelse(Reduce(`|`,lapply(word,function(pat) grepl(pat,df$column1))),"Y","N")

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...