library(stringr)
str_c
2 Join multiple strings into a single string function:
str_c("What's", " ", "next", "?")
#> [1] "What's next?"
sep
argument:
str_c("Secret", "plan", "to", "fight", "inflation", sep = " ")
#> [1] "Secret plan to fight inflation"
str_c("file", 1:5)
#> [1] "file1" "file2" "file3" "file4" "file5"
collapse
argument:
str_c("file", 1:5, collapse = ", ")
#> [1] "file1, file2, file3, file4, file5"
str_split
3 Split up a string into pieces function:
str_split("Have a cookie Sam", " ")
#> [[1]]
#> [1] "Have" "a" "cookie" "Sam"
Extract the results vector using unlist
:
unlist(str_split("Have a cookie Sam", " "))
#> [1] "Have" "a" "cookie" "Sam"
str_sub
4 Extract and replace substrings from a character vector function:
str_sub("They're all about duty", 1, 4)
#> [1] "They"
Negative indicies index from the end:
str_sub("Washington Dulles International Airport: IAD", -3, -1)
#> [1] "IAD"
str_to_upper
, str_to_lower
, str_to_title
, str_to_sentence
5 Convert case of a string. functions:
str_to_lower("LINCOLN MEMORIAL")
#> [1] "lincoln memorial"
str_to_upper("LINCOLN MEMORIAL")
#> [1] "LINCOLN MEMORIAL"
str_to_title("LINCOLN MEMORIAL")
#> [1] "Lincoln Memorial"
str_to_sentence("LINCOLN MEMORIAL")
#> [1] "Lincoln memorial"
str_trim
and str_squish
6 Trim whitespace from a string functions:
s <- " Big Bird"
writeLines(s)
#> Big Bird
writeLines(str_trim(s))
#> Big Bird
writeLines(str_squish(s))
#> Big Bird
str_detect
7 Detect the presence or absence of a pattern in a string function:
sentences <- c("You're a smart savvy woman who could easily consider world domination for a next career move.",
"I'm going to crush him. I'm going to make him cry and then I'm going to tell his momma about it.",
"Never doubt that a small group of thoughtful committed citizens can change the world.")
str_detect(sentences, "world")
#> [1] TRUE FALSE TRUE
str_extract
and str_extract_all
8 Extract matching patterns from a string functions:
header <- '
---
title: "Two Cathedrals"
author: "Aaron Sorkin"
date: "May 16, 2001"
---
'
str_extract(header, "title:.*")
#> [1] "title: \"Two Cathedrals\""
str_replace
and str_replace_all
9 Replace matched patterns in a string functions:
str_replace(sentences[2], "I'm going to", "I will")
#> [1] "I will crush him. I'm going to make him cry and then I'm going to tell his momma about it."
str_replace_all(sentences[2], "I'm going to", "I will")
#> [1] "I will crush him. I will make him cry and then I will tell his momma about it."
library(magrittr)
str_extract(header, "title:.*") %>%
str_replace("title:[ ]*", "") %>%
str_replace_all("\"", "")
#> [1] "Two Cathedrals"
Convert a glob to a regular expression via glob2rx
10 Change Wildcard or Globbing Pattern into Regular Expression function:
dir(pattern = glob2rx("*.Rmd"))
#> "eda.Rmd" "report.Rmd"