The str_remove() function from the stringr package in R can be used to remove matched patterns from a string.
This function uses the following syntax:
- string: Character vector
- pattern: Pattern to look for
The following examples show how to use this function in practice
Example 1: Use str_remove with Vector
The following code shows how to use the str_remove() function to remove the first occurrence of the pattern “e” in a vector:
library(stringr) #create character vector my_vector <- "Hey there everyone." #remove first occurrence of "e" from vector str_remove(my_vector, "e")  "Hy there everyone."
Notice that the first “e” has been removed from the vector, but all other “e” occurrences have remained.
To remove each occurrence of “e”, you can instead use the str_remove_all() function:
library(stringr) #create character vector my_vector <- "Hey there everyone." #remove all occurrences of "e" from vector str_remove_all(my_vector, "e")  "Hy thr vryon."
Notice that every occurrence of “e” has bee removed from the string this time.
Example 2: Use str_remove with Data Frame
The following code shows how to use the str_remove() function to remove the pattern “avs” from every string in a particular column of a data frame:
library(stringr) #create data frame df <- data.frame(team=c('Mavs', 'Cavs', 'Heat', 'Hawks'), points=c(99, 94, 105, 122)) #view data frame df team points 1 Mavs 99 2 Cavs 94 3 Heat 105 4 Hawks 122 #remove every occurrence of "avs" in the team column df$team <- str_remove(df$team, "avs") #view updated data frame df team points 1 M 99 2 C 94 3 Heat 105 4 Hawks 122
Notice that the pattern “avs” has been removed from the first two team names.
The following tutorials explain how to perform other common tasks in R:
How to Use str_replace in R
How to Use str_split in R
How to Use str_detect in R
How to Use str_count in R
How to Use str_pad in R