R strsplit() function - Split strings

R 语言实例R language examples

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

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

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

strsplit(x, split, fixed = FALSE)

Parameter description:

  • xInput character vector.

  • splitDelimiter, can be a fixed character or a regular expression.

  • fixedWhether to treat split as a fixed string, default is FALSE (treated as a regular expression).

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)

Running the above code produces the following result:

[1] "按逗号分割:"
[1] "张三" "李四" "王五" "赵六"
[1] "分割多个字符串:"
[[1]]
[1] "A" "B" "C"

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

strsplit() is very useful when parsing structured text:

Example

# Parse 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 sentence by spaces
sentence <- "EXAMPLE is a technical learning website"
words <- strsplit(sentence, " ")[[1]]
print("Words in the sentence:")
print(words)

Running the above code produces the following result:

[1] "年: 2026 月: 05 日: 11"
[1] "句子中的单词:"
[1] "EXAMPLE"    "是一个"    "技术学习"  "网站"

R 语言实例R language examples

Other extensions