6.13 Sub Strings in Base R

20210330 The base function base::substr() can be used to extract and replace parts of a string similar to stringr::str_sub() in the tidyverse. Note however that it does not handle negative values and that string replacement only replaces the same length as the replacement string, without changing the length of the original string.

s <- "string manipulation"
substr(s, start=3, stop=6)
## [1] "ring"
substr(s, 3, 6)
## [1] "ring"
substr(s, 1, 12) <- "stip"
s
## [1] "stipng manipulation"

The base::substring() function performs similarly though uses last= rather than stop=.

s <- "string manipulation"
substring(s, first=3, last=6)
## [1] "ring"
x <- c("abcd", "aabcb", "babcc", "cabcd")
substring(x, 2, 4)
## [1] "bcd" "abc" "abc" "abc"
substring(x, 2, 4) <- "AB"
x
## [1] "aABd"  "aABcb" "bABcc" "cABcd"


Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0