R substr() Function - Extracting and Replacing Substrings
The R substr() function is used to extract or replace a substring at specified positions in a string.
substring() is an alias of substr() and behaves basically the same.
The syntax of the substr() function is as follows:
substr(x, start, stop)
substring(text, first, last = 1000000L)
Parameter Description:
-
x/text An input string or character vector.
-
start/first The start position (starting from 1).
-
stop/last The end position.
Example
text
<-
"Hello RUNOOB"
Extract the 2nd to the 5th characters
result1
<-
substr
(
text
,
2
,
5
)
(
result1
)
Extract substrings from a vector
words
<-
c
(
"apple"
,
"banana"
,
"cherry"
)
result2
<-
substr
(
words,
1
,
3
)
(
result2
)
Replace a substring
str
<-
"Hello RUNOOB"
substr
(
str
,
7
,
12
)
<-
"WORLD"
(
str
)
The output of the code above is:
[1] "ello"
[1] "app" "ban" "che"
[1] "Hello WORLD"
substr() is often used to extract coded information in a fixed format:
Example
Extract the birth year from an ID number (positions 7-10)
id_numbers
<-
c
(
"110101199001011234"
,
"310105198505067890"
)
birth_years
<-
substr
(
id_numbers,
7
,
10
)
(
paste
(
"Birth year:"
, birth_years
)
)
The output of the code above is:
[1] "出生年份: 1990" "出生年份: 1985"
R Language Examples