How to Use the gsub() Function in R (With Examples)


The gsub() function in R can be used to replace all occurrences of certain text within a string in R.

This function uses the following basic syntax:

gsub(pattern, replacement, x) 

where:

  • pattern: The pattern to look for
  • replacement: The replacement for the pattern
  • x: The string to search

The following examples show how to use this function in practice.

Example 1: Replace Text in String

The following code shows how to replace a specific piece of text in a string:

#define string
x <- "This is a fun sentence"

#replace 'fun' with 'great'
x <- gsub('fun', 'great', x)

#view updated string
x

[1] "This is a great sentence"

Example 2: Replace Single Text String in Vector

The following code shows how to replace multiple occurrences of a text in a vector:

#define vector
x <- c('Mavs', 'Mavs', 'Spurs', 'Nets', 'Spurs', 'Mavs')

#replace 'Mavs' with 'M'
x <- gsub('Mavs', 'M', x)

#view updated vector
x

[1] "M"     "M"     "Spurs" "Nets"  "Spurs" "M"

Example 3: Replace Multiple Text Strings in Vector

The following code shows how to replace multiple occurrences of two different text strings in a vector:

#define vector
x <- c('A', 'A', 'B', 'C', 'D', 'D')

#replace 'A' or 'B' or 'C' with 'X'
x <- gsub('A|B|C', 'X', x)

#view updated string
x

[1] "X" "X" "X" "X" "D" "D"

Example 4: Replace Text in Data Frame

The following code shows how to replace text in a data frame:

#define data frame
df <- data.frame(team=c('A', 'B', 'C', 'D'),
                 conf=c('West', 'West', 'East', 'East'),
                 points=c(99, 98, 92, 87),
                 rebounds=c(18, 22, 26, 19))

#view data frame
df

  team conf points rebounds
1    A West     99       18
2    B West     98       22
3    C East     92       26
4    D East     87       19

#replace 'West' and 'East' with 'W' and 'E'
df$conf <- gsub('West', 'W', df$conf)
df$conf <- gsub('East', 'E', df$conf)

#view updated data frame
df

  team conf points rebounds
1    A    W     99       18
2    B    W     98       22
3    C    E     92       26
4    D    E     87       19

Additional Resources

How to Use diff Function in R
How to Use seq Function in R
How to Use diff Function in R
How to Use table Function in R

Leave a Reply

Your email address will not be published.