typestar

String operations in base R in R

Measuring, splitting, and rewriting character vectors.

names <- c("Ada Lovelace", "Grace Hopper")

upper <- toupper(names)
lengths <- nchar(names)
first_five <- substr(names, 1, 5)

parts <- strsplit(names, " ")
surnames <- sapply(parts, `[`, 2)
joined <- paste(names, collapse = "; ")
formatted <- sprintf("%-15s (%d chars)", names, lengths)

found <- grepl("Grace", names)
swapped <- sub("Ada", "A.", names)

How it works

  1. nchar, toupper, and substr measure and slice.
  2. strsplit splits; paste and sprintf build strings.
  3. grepl and sub match and replace by pattern.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
354
Tokens
94
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 59 seconds.

Type this snippet

Step 1 of 3 in Text & dates, step 17 of 20 in Language basics.

← Previous Next →