Skip to main content
Module 8 · Lesson 1 of 217/18 in the course~22 min
Module lessons (1/2)

Strings, Dates and Categories with factor()

Lesson preview5 hands-on exercises readyCourse R · Module 8 — Advanced Wrangling and E2E Project

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 with grepl().
  • Convert strings to time objects with as.Date() and calculate intervals with difftime() or format them with format().
  • 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

  1. 1Cleaning and text search in Base R
  2. 2Dates and time durations (as.Date, difftime, format)
  3. 3Factors with explicit and ordered levels (factor)
  4. 4Test yourself: guided exercises
  5. 5Concept check
Pro Lesson · Module 8 — Advanced Wrangling and E2E Project

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.