R 如何根据模式替换文本?

R 如何根据模式替换文本?,r,regex,stringr,R,Regex,Stringr,我有一个名为Vid1的数据集,其中包含数千行数据,如下所示: SchoolName ---------- Johns Boys Varsity Football Titan JV Football East Central Varsity Basketball Central Girls Basketball 理想情况下,我希望数据如下所示: SchoolName ---------- Johns Titan East Central Central 我已尝试使用以下代码: Vid1$S

我有一个名为Vid1的数据集,其中包含数千行数据,如下所示:

SchoolName
----------
Johns Boys Varsity Football
Titan JV Football
East Central Varsity Basketball
Central Girls Basketball
理想情况下,我希望数据如下所示:

SchoolName
----------
Johns
Titan 
East Central
Central

我已尝试使用以下代码:

Vid1$SchoolName <- str_replace_all(Vid1$SchoolName, "Boys' [a-z,A-Z]*","")
Vid1$SchoolName <- str_replace_all(Vid1$SchoolName, "Varsity Football*", "")
Vid1$SchoolName <- str_replace_all(Vid1$SchoolName, " Basketball [a-z,A-Z]*","")
Vid1$SchoolName如果您感兴趣的模式只有约翰、泰坦、中东部和中部,您可以:

library(stringr)
patts = c('Boys', 'Titan', 'Central') # add patterns here
patts = str_flatten(collapse = '|')
Vid1$SchoolName = str_remove(Vid1$SchoolName, paste0('(?<=', patts, ').*'))
库(stringr)
patts=c('Boys'、'Titan'、'Central')#在此处添加图案
patts=str_展平(collapse='|')

Vid1$SchoolName=str_remove(Vid1$SchoolName,paste0(')(?您可以尝试下一种方法,使用
stringi
定义单词向量及其替换:

#Code
#Chains
chain<-c('Varsity','Football','JV','Girls','Basketball')
replace <- c('')
#Replace
trimws(stringi::stri_replace_all_fixed(df$V1, chain, replace, vectorize_all = FALSE))

您尚未共享提取/删除文本的确切规则,因此无法从可用数据中对其进行解释

我使用了从文本中删除两个单词的逻辑,一个是运动名称,另一个是之前的单词。我们可以定义数据中存在的各种运动(例如,只有2个),并将它们粘贴到一个字符串中,然后使用
sub
将其删除

sports <- c('Football', 'Basketball')
regex_pattern <- sprintf('\\s\\w+\\s(%s)', paste0(sports, collapse = '|'))
sub(regex_pattern, '', Vid1$SchoolName)
#[1] "Johns Boys"   "Titan"        "East Central" "Central"

sports它们不是,有50000多行数据。我想我可以找到最常见的单词并从中开始。你需要找到正则表达式可以识别的模式,然后通过向量化函数将其应用于表中的所有记录,就像str_remove().我用更通用的方式编辑了答案。然后你可以添加最方便的模式
sports <- c('Football', 'Basketball')
regex_pattern <- sprintf('\\s\\w+\\s(%s)', paste0(sports, collapse = '|'))
sub(regex_pattern, '', Vid1$SchoolName)
#[1] "Johns Boys"   "Titan"        "East Central" "Central"
Vid1 <- structure(list(SchoolName = c("Johns Boys Varsity Football", 
"Titan JV Football","East Central Varsity Basketball", "Central Girls Basketball"
)), class = "data.frame", row.names = c(NA, -4L))