Library contents

R trimws

Remove whitespace at the end of a record while preserving its leading margin.

A simple example

trimws

  1. Start with " A "
  2. Do this Remove trailing spaces
  3. Result Two spaces then A
Only the spaces after A disappear.
Lesson.R
value <- "  A  "
cat(paste0("[", trimws(value, which = "right"), "]"), "\n", sep = "")
Output
[  A]

Syntax

R syntax
paste0("[", trimws(value, which = "right"), "]")
Run these examples in R

Save one example at a time as Lesson.R. Use R 4.x.

Rscript --vanilla Lesson.R

Keep the indentation of a timetable

A copied checklist or timetable contains meaningful indentation. Adjust the requested leading margin and preserve the subordinate levels so the printed layout still communicates its structure.

From the programvalue <- " Math "
Result[ Math]
Lesson.R
value <- "  Math  "
cat(paste0("[", trimws(value, which = "right"), "]"), "\n", sep = "")
Output
[  Math]

The two spaces before Math survive.

Advertisements

Clean the last field on a receipt

A terminal appends padding or a line ending to the final field it exports. Remove the trailing characters before comparing or displaying the value, while retaining the beginning of the field.

From the programvalue <- "paid\t"
Result[paid]
Lesson.R
value <- "paid\t"
cat(paste0("[", trimws(value, which = "right"), "]"), "\n", sep = "")
Output
[paid]

The trailing tab is removed.

Clean a course import

A course name arrives padded on both sides. Remove only the trailing spaces. Brackets show any indentation left at the front.

Given' Art '
Worked result[ Art]

What to watch for

The examples use ASCII padding. Check the exact whitespace definition for imported Unicode text.

Documentation for trimws