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
nchar,toupper, andsubstrmeasure and slice.strsplitsplits;pasteandsprintfbuild strings.greplandsubmatch and replace by pattern.
Keywords and builtins used here
cgreplncharpastesapplysprintfstrsplitsubsubstrtoupper
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.
Step 1 of 3 in Text & dates, step 17 of 20 in Language basics.