r中条件str_replace_all中的区分大小写

时间:2019-02-22 01:20:54

标签: r regex

例如,我有此代码。

# 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)!"

我想不区分大小写而不用降低句子。

例句:

sentence <- "I want to eat BANANA and Broccoli!"

样本输出:

[1] "I want to eat BANANA(FRUITS) and Broccoli(VEGIES)!"

1 个答案:

答案 0 :(得分:3)

您可以使用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)!"