Module lessons (1/2)
Strings, Dates and Categories with factor()
Clean up strings with trimws()/gsub()/grepl(), calculate differences between Dates and control the order of categories with factor().
What you'll learn in this lesson
- Normalize dirty text in Base R with
trimws(),tolower(),toupper(),gsub()and filter patterns withgrepl(). - Convert strings to time objects with
as.Date()and calculate intervals withdifftime()or format them withformat(). - Explicitly check the logical order of categories in
factor(..., levels = ..., ordered = TRUE)avoiding incorrect alphabetical sorting. - Prevent the classic
as.numeric()bug on factors with numeric labels.
Overview
Real datasets almost always arrive dirty: ghost spaces at the edges (" alice "), mixed separators ("BOB_verdi"), dates read as strings, and priorities listed as "high", "low", "medium" which an alphabetical sort would put in the wrong order!
grep() returns the numeric indices, while grepl() (with l trailing for logical) returns TRUE/FALSE, perfect inside the square brackets of a data.frame!
Sections covered in this lesson
- 1Cleaning and text search in Base R
- 2Dates and time durations (
as.Date,difftime,format) - 3Factors with explicit and ordered levels (
factor) - 4Test yourself: guided exercises
- 5Concept check
Unlock "Strings, Dates and Categories with factor()" and the full Course R curriculum
Clean up strings with trimws()/gsub()/grepl(), calculate differences between Dates and control the order of categories with factor().
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course R plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.