Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R gsub() Function - String Replacement

R gsub() Function - String Replacement

R Language Examples R Language Examples

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

sub() replaces only 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:

Example

text

<-

"RUNOOB is a good website, RUNOOB teaches programming, RUNOOB is worth recommending"

gsub global replacement

result1

<-

gsub

(

"RUNOOB"

,

"newbie"

,

text

)

print

(

"Global replacement:"

)

print

(

result1

)

sub replaces only the first

result2

<-

sub

(

"RUNOOB"

,

"newbie"

,

text

)

print

(

"Replace only the first:"

)

print

(

result2

)

The output of the code above is:

[1] "全局替换:"

[1] "菜鸟 是个好网站,菜鸟 教编程,菜鸟 值得推荐"

[1] "只替换第一个:"

[1] "菜鸟 是个好网站,RUNOOB 教编程,RUNOOB 值得推荐"

gsub() is very practical in data cleaning:

Example

Clean up phone number formats

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    RUNOOB   World  "

trimmed

<-

gsub

(

"\s+"

,

" "

, text_with_spaces

)

print

(

"Extra spaces removed:"

)

print

(

trim

(

trimmed

)

)

The output of the code above is:

[1] "统一格式:"

[1] "123-456-7890" "987-654-3210" "555-666-7777"

[1] "去除多余空格:"

[1] "Hello RUNOOB World"

R Language Examples R Language Examples