R strsplit
strsplit returns a list containing the pieces of each input string. fixed = TRUE treats the delimiter as literal text.
A simple example
strsplit
- Start with "a.b"
- Do this Split on a literal dot
- Result a and b
Syntax
strsplit(text, ".", fixed = TRUE)
Run this example in R
Save the program as Lesson.R. Use R 4.x.
Rscript --vanilla Lesson.R
Split literal dotted version numbers
A version identifier contains periods between components. Treat the period as a literal delimiter so the parser can recover complete version parts instead of splitting at unrelated characters.
versions <- c("2.10.4", "1.0.")
parts <- strsplit(versions, ".", fixed = TRUE)
for (n in lengths(parts)) cat(n, "parts\n")
3 parts 2 parts
A dot in a regular expression matches many characters. Using fixed mode splits only at dots. A trailing separator produces no extra final empty field in strsplit.
Count stops in a shuttle record
A timetable or route import divides each record at separators. Test the behavior at an empty field so later columns do not shift when the writer leaves a value blank.
value <- "Gate,Lab,Hall"
cat(length(strsplit(value, ",", fixed = TRUE)[[1]]), "\n", sep = "")
3
Three nonempty stop fields are present.
Handle an express route
A transit editor changes selected text in a route while preserving its remaining stops or punctuation. Identify which occurrences belong to the requested edit before rebuilding the public route label.
value <- "Depot"
cat(length(strsplit(value, ",", fixed = TRUE)[[1]]), "\n", sep = "")
1
With no delimiter the complete route is one field.