How to use str_replace in R?

str_replace() is a function in the stringr package in R that replaces all occurrences of a character or set of characters with another character or set of characters. It takes three parameters: the string to be manipulated, the character or set of characters to be replaced, and the character or set of characters to replace them with. The syntax for using str_replace is as follows: str_replace(string, find, replace). It returns a modified string as output.


The str_replace() function from the package in R can be used to replace matched patterns in a string. This function uses the following syntax:

str_replace(string, pattern, replacement)

where:

  • string: Character vector
  • pattern: Pattern to look for
  • replacement: A character vector of replacements

This tutorial provides several examples of how to use this function in practice on the following data frame:

#create data frame
df <- data.frame(team=c('team_A', 'team_B', 'team_C', 'team_D'),
                 conference=c('West', 'West', 'East', 'East'),
                 points=c(88, 97, 94, 104))

#view data frame
df

    team conference points
1 team_A       West     88
2 team_B       West     97
3 team_C       East     94
4 team_D       East    104

Example 1: Replace String with Pattern

The following code shows how to replace the string “West” with “Western” in the conference column:

library(stringr)

#replace "West" with "Western" in the conference column
df$conference <- str_replace(df$conference, "West", "Western")

#view data frame
df

    team conference points
1 team_A    Western     88
2 team_B    Western     97
3 team_C       East     94
4 team_D       East    104

Example 2: Replace String with Nothing

The following code shows how to replace the string “team_” with nothing in the team column:

#replace "team_" with nothing in the team column
df$team<- str_replace(df$team, "team_", "")

#view data frame
df

  team conference points
1    A       West     88
2    B       West     97
3    C       East     94
4    D       East    104

Example 3: Replace Multiple Strings

The following code shows how to replace multiple strings in a single column. Specifically:

  • Replace “West” with “W”
  • Replace “East” with “E”

Since we’re replacing multiple strings, we use the str_replace_all() function:

#replace multiple words in the conference column
df$conference <- str_replace_all(df$conference, c("West" = "W", "East" = "E"))

#view data frame
df

    team conference points
1 team_A          W     88
2 team_B          W     97
3 team_C          E     94
4 team_D          E    104

The following tutorials explain how to perform other common tasks in R:

How to Perform Partial String Matching in R

x