Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case sensitivity in conditional str_replace_all in r

Tags:

regex

r

For example I have this code.

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

Output:

[1] "I want to eat banana(FRUITS) and broccoli(VEGIES)!"

I want to ignore the case sensitivity without using tolower(sentence).

Sample Sentence:

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

Sample Output:

[1] "I want to eat BANANA(FRUITS) and Broccoli(VEGIES)!"
like image 789
bea Avatar asked Dec 14 '25 04:12

bea


1 Answers

You can use the regex() helper function from stringr which has an ignore_case option.

You will need to modify typeOfFood to ignore case.

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)!"
like image 81
Gregor Thomas Avatar answered Dec 15 '25 18:12

Gregor Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!