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

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

by Erma Khan

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 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 Mavs', 'Mavs', 'Spurs', 'Nets', 'Spurs', 'Mavs')

#replace 'Mavs' with 'M'
x 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 A', 'A', 'B', 'C', 'D', 'D')

#replace 'A' or 'B' or 'C' with 'X'
x 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 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 West', 'W', df$conf)
df$conf 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

Related Posts