R strsplit() Function - Splitting Strings
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:
-
x The input vector of strings.
-
split The delimiter, which can be a fixed character or a regular expression.
-
fixed Whether to treat split as a fixed string; defaults to FALSE (treated as a regular expression).
Example
Split by comma
text
<-
"Zhang San,Li Si,Wang Wu,Zhao Liu"
result
<-
strsplit
(
text
,
","
)
(
"Split by comma:"
)
(
result
[
[
1
]
]
)
Split multiple strings
texts
<-
c
(
"A-B-C"
,
"X-Y-Z"
)
result
<-
strsplit
(
texts,
"-"
)
(
"Split multiple strings:"
)
(
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
]
]
(
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
]
]
(
"Words in the sentence:"
)
(
words
)
The output of the code above is:
[1] "年: 2026 月: 05 日: 11"
[1] "句子中的单词:"
[1] "RUNOOB" "是一个" "技术学习" "网站"
R Language Examples