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

R substr() Function - Extracting and Replacing Substrings

R substr() Function - Extracting and Replacing Substrings

R Language Examples R Language Examples

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:

Example

text

<-

"Hello RUNOOB"

Extract the 2nd to the 5th characters

result1

<-

substr

(

text

,

2

,

5

)

print

(

result1

)

Extract substrings from a vector

words

<-

c

(

"apple"

,

"banana"

,

"cherry"

)

result2

<-

substr

(

words,

1

,

3

)

print

(

result2

)

Replace a substring

str

<-

"Hello RUNOOB"

substr

(

str

,

7

,

12

)

<-

"WORLD"

print

(

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

)

print

(

paste

(

"Birth year:"

, birth_years

)

)

The output of the code above is:

[1] "出生年份: 1990" "出生年份: 1985"

R Language Examples R Language Examples