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

R strsplit() Function - Splitting Strings

R strsplit() Function - Splitting Strings

R Language Examples R Language Examples

The R strsplit() function is used to split a string into multiple parts by a specified delimiter.

strsplit() returns a list, where each element is a character vector obtained from splitting the original string.

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

strsplit(x, split, fixed = FALSE)

Parameter Description:

Example

Split by comma

text

<-

"Zhang San,Li Si,Wang Wu,Zhao Liu"

result

<-

strsplit

(

text

,

","

)

print

(

"Split by comma:"

)

print

(

result

[

[

1

]

]

)

Split multiple strings

texts

<-

c

(

"A-B-C"

,

"X-Y-Z"

)

result

<-

strsplit

(

texts,

"-"

)

print

(

"Split multiple strings:"

)

print

(

result

)

The output of the code above is:

[1] "按逗号分割:"

[1] "张三" "李四" "王五" "赵六"

[1] "分割多个字符串:"

[[1]]

[1] "A" "B" "C"



[[2]]

[1] "X" "Y" "Z"

strsplit() is very useful when parsing structured text:

Example

Parse the date string "2026-05-11"

date_str

<-

"2026-05-11"

parts

<-

strsplit

(

date_str,

"-"

)

[

[

1

]

]

print

(

paste

(

"Year:"

, parts

[

1

]

,

"Month:"

, parts

[

2

]

,

"Day:"

, parts

[

3

]

)

)

Split a sentence by spaces

sentence

<-

"RUNOOB is a technology learning website"

words

<-

strsplit

(

sentence,

" "

)

[

[

1

]

]

print

(

"Words in the sentence:"

)

print

(

words

)

The output of the code above is:

[1] "年: 2026 月: 05 日: 11"

[1] "句子中的单词:"

[1] "RUNOOB"    "是一个"    "技术学习"  "网站"

R Language Examples R Language Examples