library(tidyverse)
## -- Attaching packages --------------------------------------- tidyverse 1.3.0 --
## v ggplot2 3.3.3 v purrr 0.3.4
## v tibble 3.0.6 v dplyr 1.0.4
## v tidyr 1.1.2 v stringr 1.4.0
## v readr 1.4.0 v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
library(stringr)
gettysburg <-"Four score and seven years ago our fathers brought forth, upon this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.
Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived, and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting-place for those who here gave their lives, that that nation might live. It is altogether fitting and proper that we should do this.
But, in a larger sense, we can not dedicate, we can not consecrate we can not hallow this ground. The brave men, living and dead, who struggled here, have consecrated it far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here.
It is for us, the living, rather, to be dedicated here to the unfinished work which they who fought here, have, thus far, so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us that from these honored dead we take increased devotion to that cause for which they here gave the last full measure of devotion that we here highly resolve that these dead shall not have died in vain that this nation, under God, shall have a new birth of freedom and that government of the people, by the people, for the people, shall not perish from the earth."
str1 <- 'this is a string'
str1
## [1] "this is a string"
str <- "The Alamo fell on my birthday March 6th, but in 1836, not in some year I forgot! "
str_view(str, "in")
str_view_all(str, "a")
str_view(str, "6th")
x <- c("apple", "banana", "pear")
str_view(x, ".a.")
str_view_all(x, ".?a.?")
str_view(x, "..")
str_view_all(x, "..")
‘.’ the dot matches any character except a new line
Suppose we want to match a “.” period in the string?
x<- "now is \\. not" #note the use of \ to escape itself
str_view(x, "\\\\.") #need four \ to escape the \
writeLines(x)
## now is \. not
the symbol “^” matches the beginning of a string and “$” matches the end of the string
x <- c("apple pie", "apple", "apple cake")
str_view(x, "^a")
str_view(x, "^apple")
str_view(x, "^apple$")
y <- "$^$"
str_view(y, "^\\$\\^\\$$")
x <- c("abc", "abcd", "xyy")
str_view(x, "^...$") #exactly three characters
Exercises
create regular expressions that find all words that: 1. Start with “y”.
str_view(stringr::words, "^y", match = TRUE)
str_view(stringr::words, "x$", match = TRUE)
str_view(stringr::words, "^...$", match = TRUE)
str_view(stringr::words, ".......", match = TRUE)
*Alternation | : (e.g., abc | d..f) will match either abc or deaf or dxuf
github.com/rstudio/cheatsheets/blob/master/strings.pdf
x <- c("abc", "def abc", "dead dxuf, deaf, fead")
str_view(x, "abc|d..f")
str_view
## function (string, pattern, match = NA)
## {
## if (identical(match, TRUE)) {
## string <- string[str_detect(string, pattern)]
## }
## else if (identical(match, FALSE)) {
## string <- string[!str_detect(string, pattern)]
## }
## loc <- str_locate(string, pattern)
## has_match <- !is.na(loc[, "start"])
## str_sub(string[has_match], loc[has_match, , drop = FALSE]) <- paste0("<span class='match'>",
## str_sub(string[has_match], loc[has_match, , drop = FALSE]),
## "</span>")
## str_view_widget(string)
## }
## <bytecode: 0x00000000146fa008>
## <environment: namespace:stringr>
str_view(c("grey", "gray"), "gr(e|a)y")
Exercises
str_subset(stringr::words, "^[aeiou]")
## [1] "a" "able" "about" "absolute" "accept"
## [6] "account" "achieve" "across" "act" "active"
## [11] "actual" "add" "address" "admit" "advertise"
## [16] "affect" "afford" "after" "afternoon" "again"
## [21] "against" "age" "agent" "ago" "agree"
## [26] "air" "all" "allow" "almost" "along"
## [31] "already" "alright" "also" "although" "always"
## [36] "america" "amount" "and" "another" "answer"
## [41] "any" "apart" "apparent" "appear" "apply"
## [46] "appoint" "approach" "appropriate" "area" "argue"
## [51] "arm" "around" "arrange" "art" "as"
## [56] "ask" "associate" "assume" "at" "attend"
## [61] "authority" "available" "aware" "away" "awful"
## [66] "each" "early" "east" "easy" "eat"
## [71] "economy" "educate" "effect" "egg" "eight"
## [76] "either" "elect" "electric" "eleven" "else"
## [81] "employ" "encourage" "end" "engine" "english"
## [86] "enjoy" "enough" "enter" "environment" "equal"
## [91] "especial" "europe" "even" "evening" "ever"
## [96] "every" "evidence" "exact" "example" "except"
## [101] "excuse" "exercise" "exist" "expect" "expense"
## [106] "experience" "explain" "express" "extra" "eye"
## [111] "idea" "identify" "if" "imagine" "important"
## [116] "improve" "in" "include" "income" "increase"
## [121] "indeed" "individual" "industry" "inform" "inside"
## [126] "instead" "insure" "interest" "into" "introduce"
## [131] "invest" "involve" "issue" "it" "item"
## [136] "obvious" "occasion" "odd" "of" "off"
## [141] "offer" "office" "often" "okay" "old"
## [146] "on" "once" "one" "only" "open"
## [151] "operate" "opportunity" "oppose" "or" "order"
## [156] "organize" "original" "other" "otherwise" "ought"
## [161] "out" "over" "own" "under" "understand"
## [166] "union" "unit" "unite" "university" "unless"
## [171] "until" "up" "upon" "use" "usual"
(2) That only contain consonants. (Hint: thinking about matching “not”-vowels.)
str_view(stringr::words, "[aeiou]", match=FALSE)
(3) End with ed, but not with eed.
str_view(stringr::words, "[^e]ed$", match = TRUE)
(4) End with ing or ise.
str_view(stringr::words, "i(ng|se)", match = TRUE)
str_view(stringr::words, "([^c]ie)", match = TRUE)
str_view(stringr::words, "q[^u]", match = TRUE)
Yes, in stringr::words dataset.
str_view(stringr::words, "ou|ise$", match = TRUE)
str_view(x, “\d\d\d-\d\d\d-\d\d\d\d”)
Controlling how many times a pattern matches
? matches 0 or 1 occurence + matches 1 or more occurences * 0 or more occurences
x <- "1888 is the longest year in (unmodified) Roman numerals: MDCCCLXXXVIII"
str_view(x, "CC?")
str_view(x, "CC+")
str_view(x, "C[LX]+")
{n} exactly n times {n,} n or more times {,m} at most m times {n,m} between n and m times
str_view(fruit, "(..)\\1a", match = TRUE)
Exercises:
? -> {0,1} + -> {1,} * -> {0,}
str_view(words, "^[^aeiou]{3}", match = TRUE)
str_view(words, "[aeiou]{3,}", match = TRUE)
str_view(words, "([aeiou][^aeiou]){2,}", match = TRUE)
str_detect is used to select elements that match a pattern.
x <- c("apple", "banana", "pear")
str_detect(x, "e")
## [1] TRUE FALSE TRUE
# How many common words start with t?
sum(str_detect(words, "^t"))
## [1] 65
# What proportion of common words end with a vowel?
mean(str_detect(words, "[aeiou]$"))
## [1] 0.2765306
# Find all words containing at least one vowel, and negate
no_vowels_1 <- !str_detect(words, "[aeiou]")
# Find all words consisting only of consonants (non-vowels)
no_vowels_2 <- str_detect(words, "^[^aeiou]+$")
identical(no_vowels_1, no_vowels_2)
## [1] TRUE
#> [1] TRUE
An alternative to str_detect is str_subset()
words[str_detect(words, "x$")]
## [1] "box" "sex" "six" "tax"
str_subset(words, "x$")
## [1] "box" "sex" "six" "tax"
df <- tibble (
word = words,
i = seq_along(word)
)
df %>%
filter(str_detect(words, "x$"))
## # A tibble: 4 x 2
## word i
## <chr> <int>
## 1 box 108
## 2 sex 747
## 3 six 772
## 4 tax 841
A variation on str_detect() is str_count(): rather than yes or no, it tells you how many matches there are in a string:
str_count(words, "a")
## [1] 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 2 2 1 1 1 1 1 1 1 1 1 2 1 1 1 2 2 1
## [38] 1 1 1 1 2 2 2 1 1 2 2 2 1 1 1 2 1 1 1 2 1 1 1 1 3 2 2 1 1 1 1 1 2 1 1 1 1
## [75] 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 0
## [112] 1 0 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 2 1 1 1 2 1 1 0 0 0
## [149] 0 0 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1
## [186] 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 1
## [223] 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 1 1 1 0 1 0
## [260] 0 0 0 0 0 0 0 0 1 0 0 0 0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0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1
## [778] 0 0 1 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 1 1 2 1 1 1 1 0 0 0 0 0 1 1 0 0
## [815] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0
## [852] 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 1 0 1 1 1 1
## [889] 1 1 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 1 0 0 1 1 1 1
## [926] 1 1 1 1 1 1 1 1 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
## [963] 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0
Use str_count() with mutate()
df %>%
mutate(vowels = str_count(word, "[aeiou]"),
consonants = str_count(word, "[^aeiou]")) %>%
arrange(desc(consonants), vowels)
## # A tibble: 980 x 4
## word i vowels consonants
## <chr> <int> <int> <int>
## 1 Christmas 151 2 7
## 2 transport 888 2 7
## 3 department 222 3 7
## 4 photograph 617 3 7
## 5 understand 903 3 7
## 6 environment 275 4 7
## 7 opportunity 581 4 7
## 8 responsible 703 4 7
## 9 contract 187 2 6
## 10 district 234 2 6
## # ... with 970 more rows
Exercises
words[str_detect(words, "^x|x$")]
## [1] "box" "sex" "six" "tax"
str_subset(words, "^[aeiou].*[^aeiou]$")
## [1] "about" "accept" "account" "across" "act"
## [6] "actual" "add" "address" "admit" "affect"
## [11] "afford" "after" "afternoon" "again" "against"
## [16] "agent" "air" "all" "allow" "almost"
## [21] "along" "already" "alright" "although" "always"
## [26] "amount" "and" "another" "answer" "any"
## [31] "apart" "apparent" "appear" "apply" "appoint"
## [36] "approach" "arm" "around" "art" "as"
## [41] "ask" "at" "attend" "authority" "away"
## [46] "awful" "each" "early" "east" "easy"
## [51] "eat" "economy" "effect" "egg" "eight"
## [56] "either" "elect" "electric" "eleven" "employ"
## [61] "end" "english" "enjoy" "enough" "enter"
## [66] "environment" "equal" "especial" "even" "evening"
## [71] "ever" "every" "exact" "except" "exist"
## [76] "expect" "explain" "express" "identify" "if"
## [81] "important" "in" "indeed" "individual" "industry"
## [86] "inform" "instead" "interest" "invest" "it"
## [91] "item" "obvious" "occasion" "odd" "of"
## [96] "off" "offer" "often" "okay" "old"
## [101] "on" "only" "open" "opportunity" "or"
## [106] "order" "original" "other" "ought" "out"
## [111] "over" "own" "under" "understand" "union"
## [116] "unit" "university" "unless" "until" "up"
## [121] "upon" "usual"
words[str_detect(words, "a") &
str_detect(words, "e") &
str_detect(words, "i") &
str_detect(words, "o") &
str_detect(words, "u")]
## character(0)
vowels <- str_count(words, "[aeiou]")
words[which(vowels == max(vowels))]
## [1] "appropriate" "associate" "available" "colleague" "encourage"
## [6] "experience" "individual" "television"
length(sentences)
## [1] 720
head(sentences)
## [1] "The birch canoe slid on the smooth planks."
## [2] "Glue the sheet to the dark blue background."
## [3] "It's easy to tell the depth of a well."
## [4] "These days a chicken leg is a rare dish."
## [5] "Rice is often served in round bowls."
## [6] "The juice of lemons makes fine punch."
Find all sentences that contain a color
colors <- c("red", "orange", "yellow", "green", "blue", "purple")
color_match <- str_c(colors, collapse = "|")
color_match
## [1] "red|orange|yellow|green|blue|purple"
Select the sentences that contain a colour, and then extract the colour to figure out which one it is:
has_colour <- str_subset(sentences, color_match)
matches <- str_extract(has_colour, color_match)
head(matches)
## [1] "blue" "blue" "red" "red" "red" "blue"
str_extract() only extracts the first match. We can see that most easily by first selecting all the sentences that have more than 1 match:
more <- sentences[str_count(sentences, color_match) > 1]
str_view_all(more, color_match)
str_extract(more, color_match)
## [1] "blue" "green" "orange"