library(stringr)
str_length(c("ab", "R for data science", NA)) #>[1] 2 18 NA
To combine two or more strings, you can use the str_c() function:
str_c("x", "y", "z") #>[1] "xyz"
You can use the sep parameter to control the separation between strings:
str_c("x", "y", sep = ", ") #>[1] "x, y"
The str_c() function is vectorized, it can automatically loop the short vector so that it has the same length as the longest vector:
str_c("prefix-", c("a", "b", "c"), "-suffix") #> [1] "prefix-a-suffix" "prefix-b-suffix" "prefix-c-suffix"
To merge character vectors into strings, you can use the collapse() function:
str_c(c("x", "y", "z"), collapse = ", ") #> [1] "x, y, z"
You can use the str_sub() function to extract part of the string. In addition to string parameters, there are start and end parameters in the str_sub() function, which give the position of the substring (including start and end):
x <- c("Apple", "Banana", "Pear") str_sub(x, 1, 3) #> [1] "App" "Ban" "Pea"
Negative number means counting from back to front
str_sub(x, -3, -1) #> [1] "ple" "ana" "ear"
str_to_upper(c("a", "b")) #>[1] "A" "B" str_sub(x, 1, 1) <- str_to_lower(str_sub(x, 1, 1)) x #> [1] "apple" "banana" "pear"