R gsub() Function - String Replacement

R 语言实例R Language Examples

The R gsub() function is used to globally replace matching parts in a string.

sub() only replaces the first match, while gsub() replaces all matches.

The syntax of the gsub() function is as follows:

gsub(pattern, replacement, x)
sub(pattern, replacement, x)

Parameter description:

  • patternThe pattern to match (supports regular expressions).

  • replacementThe replacement string.

  • xInput string vector.

Example

text <- "EXAMPLE is a good website, EXAMPLE teaches programming, EXAMPLE is worth recommending"

# gsub global replacement
result1 <- gsub("EXAMPLE", "Rookie", text)
print("Global replacement:")
print(result1)

# sub only replaces the first
result2 <- sub("EXAMPLE", "Rookie", text)
print("Only replace the first:")
print(result2)

Executing the above code produces the following output:

[1] "全局替换:"
[1] "Example 是个好网站,Example 教编程,Example 值得推荐"
[1] "只替换第一个:"
[1] "Example 是个好网站,EXAMPLE 教编程,EXAMPLE 值得推荐"

gsub() is very practical in data cleaning:

Example

# Clean up phone number format
phone_numbers <- c("123-456-7890", "987.654.3210",
                   "555 666 7777")
# Replace all non-digit characters with -
clean <- gsub("[^0-9]", "-", phone_numbers)
print("Unified format:")
print(clean)

# Remove extra spaces
text_with_spaces <- "  Hello    EXAMPLE   World  "
trimmed <- gsub("\\s+", " ", text_with_spaces)
print("Remove extra spaces:")
print(trim(trimmed))

Executing the above code produces the following output:

[1] "统一格式:"
[1] "123-456-7890" "987-654-3210" "555-666-7777"
[1] "去除多余空格:"
[1] "Hello EXAMPLE World"

R 语言实例R Language Examples

Other Extensions