Library contents

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

  1. Start with "a.b"
  2. Do this Split on a literal dot
  3. Result a and b
Treating the dot as literal punctuation makes it the field separator.

Syntax

R 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.

First output line3 parts
Lesson.R
versions <- c("2.10.4", "1.0.")
parts <- strsplit(versions, ".", fixed = TRUE)
for (n in lengths(parts)) cat(n, "parts\n")
Output
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.

R documentation for strsplit

Advertisements

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.

From the programvalue <- "Gate,Lab,Hall"
Result3
Lesson.R
value <- "Gate,Lab,Hall"
cat(length(strsplit(value, ",", fixed = TRUE)[[1]]), "\n", sep = "")
Output
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.

From the programvalue <- "Depot"
Result1
Lesson.R
value <- "Depot"
cat(length(strsplit(value, ",", fixed = TRUE)[[1]]), "\n", sep = "")
Output
1

With no delimiter the complete route is one field.