Chapter 6 Working with Strings

First load the package.

library(stringr)

6.1 String combine with str_c

our_string = c("With", "great", "power", "comes", "great", "responsibility")

str_length(our_string)
## [1]  4  5  5  5  5 14
str_c("Hello", "World", sep = " ")
## [1] "Hello World"
str_c(our_string)
## [1] "With"           "great"          "power"          "comes"         
## [5] "great"          "responsibility"
str_c(our_string,  collapse = " ")
## [1] "With great power comes great responsibility"

6.2 Substrings with str_sub

str_sub(our_string, 1, 1)
## [1] "W" "g" "p" "c" "g" "r"
str_sub(our_string, 1, 2)
## [1] "Wi" "gr" "po" "co" "gr" "re"
str_sub(our_string, -1, -1)
## [1] "h" "t" "r" "s" "t" "y"
str_sub(our_string, -2, -1)
## [1] "th" "at" "er" "es" "at" "ty"

6.3 Capitalize or not

str_to_lower(our_string)
## [1] "with"           "great"          "power"          "comes"         
## [5] "great"          "responsibility"
str_to_upper(our_string)
## [1] "WITH"           "GREAT"          "POWER"          "COMES"         
## [5] "GREAT"          "RESPONSIBILITY"
str_to_title(our_string)
## [1] "With"           "Great"          "Power"          "Comes"         
## [5] "Great"          "Responsibility"
# specify locale to be sure that behavior is consistent with locale option
str_to_title(our_string, locale = "en")
## [1] "With"           "Great"          "Power"          "Comes"         
## [5] "Great"          "Responsibility"
# capitalize first letter
str_sub(our_string, 1, 1) <- str_to_upper(str_sub(our_string, 1, 1))
our_string
## [1] "With"           "Great"          "Power"          "Comes"         
## [5] "Great"          "Responsibility"

6.4 String sort

str_sort(our_string)
## [1] "Comes"          "Great"          "Great"          "Power"         
## [5] "Responsibility" "With"

6.5 Handling NAs

another_string = c(NA, "Hello", "World")
str_c(another_string, collapse = " ")
## [1] NA