A little announcement. A lot to explore.

Happy learning!

Explore lessons, including SAS & R programs and practice data.

Search lessons

Type at least 3 characters to see matching lessons.

Open SAS ↗Open R ↗
← SASnRCompress or remove specific characters

Introduction

  • Raw text values coming from EDC, external vendors, lab files or manual entry are often messy — extra spaces, stray punctuation, mixed separators like slashes and dashes, or special characters that we do not want in the analysis.
  • Before we can match, group, merge or summarise such values reliably, we typically clean them up by dropping unwanted characters.
  • SAS calls this operation compressing a string — the COMPRESS() function either strips a given set of characters or, with the "k" (keep) modifier, strips everything except a given set.
  • R does not have a dedicated "compress" function. We use str_remove_all() (tidyverse stringr) or gsub() (base R) with a pattern. A plain string removes literal characters; a regular expression removes a class of characters.
  • What to expect from the examples below:
    • A small input dataset with six deliberately messy text values.
    • Five cleaned columns showing common tasks: drop spaces only, drop any whitespace, drop slashes and dashes, keep only digits, keep only letters and digits.
    • The SAS, tidyverse and base R versions produce the same five columns so we can compare the syntax side by side.
  • After running, inspect compress02 (or the R equivalent) and confirm each new column reflects the intended rule. For example, digits_only on row 4 should contain only 015.

Compress or remove specific characters