Home » How to Use str_replace in R (With Examples)

How to Use str_replace in R (With Examples)

by Tutor Aspire

The str_replace() function from the stringr 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 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$teamstr_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

Additional Resources

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

How to Perform Partial String Matching in R
How to Convert Strings to Dates in R
How to Convert Character to Numeric in R

You may also like