Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 39 / 68

Normalizing strings (trimws and case)

This lesson covers normalizing strings in R, with the aim of comparing text that is written inconsistently.

Text typed by a user tends to carry stray whitespace at the ends and inconsistent capitalisation. Stripping the whitespace with trimws() and unifying the case with tolower() is called normalization.

The sample code runs tolower(trimws(s)) inside a normalize() function, stripping the surrounding whitespace and then lower-casing. Two strings that look different — " Hello World " and "hello world" — compare as the same once normalized.

A common early stumble is comparing without this step. Two strings that look identical to a person can come back FALSE, which makes for a bug that is hard to track down.

In professional work, normalization is an indispensable preprocessing step for unifying inconsistent data read from a CSV.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)