6.14 Sub Strings in the Tidyverse

20180607 We will find ourselves often wanting to extract or modify sub-strings within a string. The tidy way to do this is with the stringr::str_sub() function. We can specify the start= and the end= of the string. The indices of the string start from 1.

s <- "string manipulation"
str_sub(s, start=3, end=6)
## [1] "ring"
str_sub(s, 3, 6)
## [1] "ring"

A negative is used to count from the end of the string.

str_sub(s, 1, -8)
## [1] "string manip"

Replacing a sub-string with another string is straightforward using the assignment operator.

str_sub(s, 1, -8) <- "stip"
s
## [1] "stipulation"

The function also operates over a vector of strings.

v <- c("string", "manipulation", "always", "fascinating")
str_sub(v, -4, -1)
## [1] "ring" "tion" "ways" "ting"
str_sub(v, -4, -1) <- "RING"
v
## [1] "stRING"       "manipulaRING" "alRING"       "fascinaRING"


Your donation will support ongoing development 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-2021 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0.