Go to TogaWare.com Home Page. Data Science Desktop Survival Guide
by Graham Williams
Duck Duck Go



CLICK HERE TO VISIT THE UPDATED SURVIVAL GUIDE

Sub-Strings in Base R

The base function base::substr() can be used to extract and replace parts of a string similar to stringr::str_sub(). 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"


Support further development by purchasing the PDF version of the book.
Other online resources include the GNU/Linux Desktop Survival Guide.
Books available on Amazon include Data Mining with Rattle and Essentials of Data Science.
Popular open source software includes rattle and wajig.
Hosted by Togaware, a pioneer of free and open source software since 1984.
Copyright © 2000-2020 Togaware Pty Ltd. . Creative Commons ShareAlike V4.