To remove several words from a string using the 'stringr' package in R, you can utilize the 'str_remove_all()' or 'str_replace_all()' functions. Here's an example:

library(stringr)

remove_words <- c('apple', 'banana', 'orange')
text <- 'I like apple, banana, and orange.'

# Remove words using str_remove_all()
clean_text <- str_remove_all(text, paste0('\b(', paste(remove_words, collapse = '|'), ')\b'))
print(clean_text)
# Output: 'I like , , and .'

# Remove words using str_replace_all()
clean_text <- str_replace_all(text, paste0('\b(', paste(remove_words, collapse = '|'), ')\b'), '')
print(clean_text)
# Output: 'I like , , and .'

In this example, we first define the words to be removed in the 'remove_words' vector. Subsequently, we define the input text in the 'text' variable. We can use either 'str_remove_all()' or 'str_replace_all()' functions to remove the words.

In 'str_remove_all()', we utilize the 'paste0()' function to concatenate the words in the 'remove_words' vector with the '|' separator to create a regular expression pattern. We employ the '\b' word boundary to ensure that only complete words are matched and removed. The resulting clean text is stored in the 'clean_text' variable.

Similarly, in 'str_replace_all()', we use the same regular expression pattern to match the words and replace them with an empty string. The resulting clean text is also stored in the 'clean_text' variable.

Remove Multiple Words from a String in R using stringr

原文地址: https://www.cveoy.top/t/topic/y6X 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录