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)!"
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)!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With