文本替换——模式是字符串的集合列表[r]

文本替换——模式是字符串的集合列表[r],r,apply,code-cleanup,stringr,text-manipulation,R,Apply,Code Cleanup,Stringr,Text Manipulation,我在一个大数据集中有一个字符串变量,我想根据一组字符串列表来清理它。例如,pattern我们将“pattern”向量粘贴在一起以创建一个字符串,在将“vec1”改为小写(tolower(vec1))后,使用该字符串从“vec1”中提取单词 数据 pattern使用base R的另一种方法是: #data vec <- c('black Dog', 'white dOG', 'doggie','black CAT','thatdamcat') #regexpr finds the loca

我在一个大数据集中有一个字符串变量,我想根据一组字符串列表来清理它。例如,pattern我们
将“pattern”向量粘贴在一起以创建一个字符串,在将“vec1”改为小写(
tolower(vec1)
)后,使用该字符串从“vec1”中提取单词

数据
pattern使用base R的另一种方法是:

#data
vec <- c('black Dog', 'white dOG', 'doggie','black CAT','thatdamcat')

#regexpr finds the locations of cat and dog ignoring the cases
a <- regexpr( 'dog|cat', vec, ignore.case=TRUE )

#regmatches returns the above locations from vec (here we use tolower in order 
#to convert to lowercase)
regmatches(tolower(vec), a)
[1] "dog" "dog" "dog" "cat" "cat"
#数据

vec我也试过这个,它也能工作,但它不是我想要的,因为我的数据集中也有“bird”,我想要一个NA占位符。我的解释错了。非常感谢。
dog
dog
dog
cat
cat
new <- vector()

lapply(pattern, function(x){
  where<- grep(x,a,value = FALSE, ignore.case = TRUE)
  new[where]<-x
  })
library(stringr)
str_extract(tolower(vec1), paste(pattern, collapse='|'))
#[1] "dog" "dog" "dog" "cat" "cat"
pattern <- c("dog","cat") 
vec1 <- c('black Dog', 'white dOG', 'doggie','black CAT', 'thatdamcat')
#data
vec <- c('black Dog', 'white dOG', 'doggie','black CAT','thatdamcat')

#regexpr finds the locations of cat and dog ignoring the cases
a <- regexpr( 'dog|cat', vec, ignore.case=TRUE )

#regmatches returns the above locations from vec (here we use tolower in order 
#to convert to lowercase)
regmatches(tolower(vec), a)
[1] "dog" "dog" "dog" "cat" "cat"