R gsub() Function - String Replacement
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:
-
pattern The pattern to match (supports regular expressions).
-
replacement The string to replace with.
-
x The input vector of strings.
Example
text
<-
"RUNOOB is a good website, RUNOOB teaches programming, RUNOOB is worth recommending"
gsub global replacement
result1
<-
gsub
(
"RUNOOB"
,
"newbie"
,
text
)
(
"Global replacement:"
)
(
result1
)
sub replaces only the first
result2
<-
sub
(
"RUNOOB"
,
"newbie"
,
text
)
(
"Replace only the first:"
)
(
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
)
(
"Unified format:"
)
(
clean
)
Remove extra spaces
text_with_spaces
<-
" Hello RUNOOB World "
trimmed
<-
gsub
(
"\s+"
,
" "
, text_with_spaces
)
(
"Extra spaces removed:"
)
(
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