r - r中条件str_replace_all的大小写敏感性
问题描述
例如我有这个代码。
# Lookup List
fruits <- c("guava","avocado", "apricots","kiwifruit","banana")
vegies <- c("tomatoes", "asparagus", "peppers", "broccoli", "leafy greens")
# Patterns
foods <- c("guava", "banana", "broccoli")
patterns <- str_c(foods, collapse="|")
# Sample Sentence
sentence <- "I want to eat banana and broccoli!"
typeOfFood <- function(foods) {
if( foods %in% fruits ){
type <- "FRUITS"
}
else if( foods %in% vegies ){
type <- "VEGIES"
}
paste0(foods,"(",type,")")
}
str_replace_all(sentence, patterns, typeOfFood)
输出:
[1] "I want to eat banana(FRUITS) and broccoli(VEGIES)!"
我想在不使用 tolower(sentence) 的情况下忽略区分大小写。
例句:
sentence <- "I want to eat BANANA and Broccoli!"
样本输出:
[1] "I want to eat BANANA(FRUITS) and Broccoli(VEGIES)!"
解决方案
您可以使用具有选项的regex()
辅助函数。stringr
ignore_case
您将需要修改typeOfFood
以忽略大小写。
typeOfFood <- function(foods) {
if(tolower(foods) %in% fruits ){
type <- "FRUITS"
}
else if(tolower(foods) %in% vegies ){
type <- "VEGIES"
}
paste0(foods,"(",type,")")
}
sentence <- "I want to eat BANANA and Broccoli!"
str_replace_all(sentence, regex(patterns, ignore_case = TRUE), typeOfFood)
# [1] "I want to eat BANANA(FRUITS) and Broccoli(VEGIES)!"
推荐阅读
- c# - 在 C# 中使用 System 指令时找不到类型或命名空间名称“文本”
- javascript - 获取值仅使用 .first 有效,但如果我尝试使用 .each 循环每个项目,它什么也不做
- gnuradio - 无法使“FM_receiver”示例 gnuradio 代码工作
- automata - 如何为特定范围的二进制数绘制 DFA?
- android - MPAndroidChart 正确使用 getPixelForValues 为图表渐变颜色
- csv - 为什么 Google 数据工作室 csv 连接器工作不正常
- macos - 错误“sh: : command not found sh: : command not found”编号 127
- laravel - Is it possible to make the user section of my website a SPA and the admin section MPA in laravel
- docker - 可以在 Gitlab CI/CD 上缓存 docker-compose 吗?
- c++ - How to store a series of SFML sprites