stringr::str_replace() and stringr::str_replace_all()
   get_help() docs


Description

The str_replace() and str_replace_all() functions are part of the {stringr} package, which is part of the {tidyverse}.

We use these function find and replace patterns, including strings or or regular expression (a special type of pattern-matching string), in strings.

The str_replace() function will replace only the first occurrence of the given pattern with the given replacement, but str_replace_all() will replace all occurrences of the given pattern with the given replacement.

All {stringr} functions (and R itself) are case sensitive, which means uppercase and lowercase letters are viewed as different characters. In other words, searching for “A” will not match “a”, and searching for “a” will not match “A.”

To use this function, you need to either first load the {stringr} library, or always use the function with stringr::() notation.

# Load the library
library(stringr)
# Or, load the full tidyverse:
library(tidyverse)

# Or, use :: notation with str_replace(), for example
stringr::str_replace()

Conceptual Usage

stringr::str_replace("string to search in", 
                     "pattern to search for",
                     "replacement to replace only the first occurrance of pattern")

stringr::str_replace_all("string to search in", 
                         "pattern to search for",
                         "replacement to replace all occurrances")

Examples

The examples use the variables shown below, as well as the carnivores dataset. Learn more about the carnivores with get_help("carnivores").

# Show all variables and datasets used in examples:

# A single string
single_sentence
## [1] "No doubt about the way the wind blows."

# An array of strings
fruits
## [1] "kiwi fruit" "pomelo"     "goji berry" "persimmon"  "mulberry"   "raspberry"

# A tibble
carnivores
## # A tibble: 9 × 4
##   name              genus        awake brainwt
##   <chr>             <fct>        <dbl>   <dbl>
## 1 Arctic fox        Vulpes        11.5  0.0445
## 2 Cheetah           Acinonyx      11.9 NA     
## 3 Dog               Canis         13.9  0.07  
## 4 Gray seal         Haliochoerus  17.8  0.325 
## 5 Jaguar            Panthera      13.6  0.157 
## 6 Lion              Panthera      10.5 NA     
## 7 Northern fur seal Callorhinus   15.3 NA     
## 8 Red fox           Vulpes        14.2  0.0504
## 9 Tiger             Panthera       8.2 NA


# Replace the first occurrances of "the" with "THE" in single_sentence
str_replace(single_sentence, "the", "THE")
## [1] "No doubt about THE way the wind blows."


# Replace all  occurranceso f "the" with "THE" in single_sentence
str_replace_all(single_sentence, "the", "THE")
## [1] "No doubt about THE way THE wind blows."


# Replace the first occurrence of letter "i" with the word "EYE" in all strings in fruits
# This will replace the first occurrence separately in each string in fruits
str_replace(fruits, "i", "EYE")
## [1] "kEYEwi fruit" "pomelo"       "gojEYE berry" "persEYEmmon"  "mulberry"     "raspberry"


# Replace all occurrence of letter "i" with the word "EYE" in all strings in fruits
str_replace_all(fruits, "i", "EYE")
## [1] "kEYEwEYE fruEYEt" "pomelo"           "gojEYE berry"     "persEYEmmon"     
## [5] "mulberry"         "raspberry"


# Replace all occurrences of the substring "berry" with "bear-y" in all fruit strings
# When you know you want all occurrences replaced, it's generally safer to use `str_replace_all()`
str_replace_all(fruits, "berry", "bear-y")
## [1] "kiwi fruit"  "pomelo"      "goji bear-y" "persimmon"   "mulbear-y"   "raspbear-y"


# Use dplyr::mutate() to create a new column `name_improved` in carnivores that 
#   replaces all occurrences of "seal" in the column `name` with "furbabies"
carnivores %>%
  dplyr::mutate(name_improved = str_replace_all(name, "seal", "furbabies"))
## # A tibble: 9 × 5
##   name              genus        awake brainwt name_improved         
##   <chr>             <fct>        <dbl>   <dbl> <chr>                 
## 1 Arctic fox        Vulpes        11.5  0.0445 Arctic fox            
## 2 Cheetah           Acinonyx      11.9 NA      Cheetah               
## 3 Dog               Canis         13.9  0.07   Dog                   
## 4 Gray seal         Haliochoerus  17.8  0.325  Gray furbabies        
## 5 Jaguar            Panthera      13.6  0.157  Jaguar                
## 6 Lion              Panthera      10.5 NA      Lion                  
## 7 Northern fur seal Callorhinus   15.3 NA      Northern fur furbabies
## 8 Red fox           Vulpes        14.2  0.0504 Red fox               
## 9 Tiger             Panthera       8.2 NA      Tiger