r - 如何根据模式替换文本?
问题描述
我有一个名为 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]*","")
对于某些人来说,输出并不理想。有人有建议吗?
解决方案
您可以尝试下一种方法来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"
推荐阅读
- python-3.x - 将过滤器应用于霍夫线检测
- maven - Maven Tycho 尝试解压缩签名文件时失败(tycho-packaging-plugin)
- linux - 一种指定命令在前一个失败时运行的方法
- arrays - 在给定数组中查找 LCM 值最小的对
- mysql - 查找缺少某些子项的行
- python - 如何通过金字塔中的粘贴 get_app 函数读取 2 个不同的 ini 文件?
- javascript - 如何在 Swiper Cover Flow Slider 中更改幻灯片的渲染流程
- php - 为什么我在 PHP 中的表填充了表属性而不是字段(使用远程 DB 用于 Asterisk CDR)?
- mysql - 将生成的文本文件加载到 MySQL 表时,会插入一个奇怪的字符
- c# - IC# treeView 显示文件夹序列节点如何重命名节点在表单加载时循环而不更改源文件夹名称