首页 > 解决方案 > 如何根据模式替换文本?

问题描述

我有一个名为 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]*","")

对于某些人来说,输出并不理想。有人有建议吗?

标签: rregexstringr

解决方案


您可以尝试下一种方法来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))

输出:

[1] "Johns Boys"   "Titan"        "East Central" "Central"

推荐阅读