-
Notifications
You must be signed in to change notification settings - Fork 8
/
14-strings.Rmd
770 lines (573 loc) · 23.7 KB
/
14-strings.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
```{r setup14, include=FALSE, message=FALSE, warning=FALSE}
knitr::opts_chunk$set(echo = TRUE, cache = TRUE)
library(ggplot2)
library(dplyr)
library(tidyr)
library(stringr)
library(stringi)
```
# Ch. 14: Strings
```{block2, type='rmdimportant'}
**Key questions:**
* 14.2.5. #3, 6
* 14.3.2.1. #2
* 14.3.3.1 #1, #2
```
```{block2, type='rmdtip'}
**Functions and notes:**
```
* `writeLines`: see raw contents of a string (prints each string in a vector on a new line)
* `str_length`: number of characters in a string
* `str_c`: combine two or more strings
* use `collapse` arg to make vector of strings to single string
* `str_replace_na`: print `NA` as "NA"
* `str_sub`: `start` and `end` args to specify position to remove (or replace), can use negative numbers as well to represent from back
* `str_to_lower`, `str_to_upper`, `str_to_upper`: for changing string case
* `locale` arg (to handle slight differences in characters)
* `str_order`, `str_sort`: more robust version of `order` and `sort` which take allow a `locale` argument
* `str_view`, `str_view_all`: shows how character and regular expression match
* `\d`: matches any digit.
* `\s`: matches any whitespace (e.g. space, tab, newline).
* `[abc]`: matches a, b, or c.
* `[^abc]`: matches anything except a, b, or c.
* `{n}`: exactly n
* `{n,}`: n or more
* `{,m}`: at most m
* `{n,m}`: between n and m
* `str_detect`: returns logical vector of `TRUE`/`FALSE` values
* `str_subset`: subset of `TRUE` values from `str_detect`
* `str_count`: number of matches in a string
* `str_extract`: extract actual text of a match
* `str_extract_all`: returns list with all matches
* `simplify = TRUE` returns a matrix
* `str_match`: similar to `str_extract` but gives each individual component of match in a matrix, rather than a character vector (also have a `str_match_all`)
* `tidyr::extract`: like `str_match` but name columns with matches which are moved into new columns
* `str_replace`, `str_replace_all`: replace matches with new strings
* `str_split` split a string into pieces -- default is individual words (returns list)
* `simplify = TRUE` again will return a matrix
* `boundary` use to specify level of split, e.g. `str_view_all(x, boundary("word"))`
* `str_locate`, `str_locate_all`: gives starting an dending positions of each match
* `regex` use in match to specify more options, e.g. `str_view(bananas, regex("banana", ignore_case = TRUE))`
* `multiline = TRUE` allows `^` and `$` to match start and end of each line (rather than of string)
* `comments = TRUE` allows you to add comments on a complex regular expression
* `dotall = TRUE` allows `.` to match more than just letters e.g. `\\n`
* `fixed`, `coll` related alternatives to `regex`
* `apropos` searches all objects available from global environment (e.g. say you can't remember function name)
* `dir`: lists all files in a directory
* `pattern` arg takes a regex
* `stringi` more comprehensive package than `stringr` (~5x as many funs)
## 14.2: String basics
Use `wrteLines` to show what string 'This string has a \\n new line' looks like printed.
```{r}
string_exp <- 'This string has a \n new line'
print(string_exp)
writeLines(string_exp)
```
To see full list of specifal characters:
```{r, eval = FALSE}
?'"'
```
Objects of length 0 are silently dropped. This is particularly useful in conjunction with `if`:
```{r}
name <- "Bryan"
time_of_day <- "morning"
birthday <- FALSE
str_c(
"Good ", time_of_day, " ", name,
if (birthday) " and HAPPY BIRTHDAY",
"."
)
```
Collapse vectors into single string
```{r}
str_c(c("x", "y", "z"), c("a", "b", "c"), collapse = ", ")
```
Can use assignment form of `str_sub()`
```{r}
x <- c("Apple", "Banana", "Pear")
str_sub(x, 1, 1) <- str_to_lower(str_sub(x, 1, 1))
x
```
`str_pad` looks interesting
```{r}
str_pad("the dogs come for you.", width = 40, pad = ",", side = "both") #must specify width =, side = default is left
```
### 14.2.5
1. *In code that doesn't use stringr, you'll often see `paste()` and `paste0()`. What's the difference between the two functions?*
* `paste0()` has no `sep` argument and just appends any value provided like another string vector.
* They differ from `str_c()` in that they automatically convert `NA` values to character.
```{r}
paste("a", "b", "c", c("x", "y"), sep = "-")
paste0("a", "b", "c", c("x", "y"), sep = "-")
```
*What `stringr` function are they equivalent to?*
`paste()` and `paste0()` are similar to `str_c()` though are different in how they handle NAs (see below). They also will return a warning when recycling vectors whose legth do not have a common factor.
```{r}
paste(c("a", "b", "x"), c("x", "y"), sep = "-")
str_c(c("a", "b", "x"), c("x", "y"), sep = "-")
```
*How do the functions differ in their handling of `NA`?*
```{r}
paste(c("a", "b"), c(NA, "y"), sep = "-")
str_c(c("a", "b"), c(NA, "y"), sep = "-")
```
1. *In your own words, describe the difference between the `sep` and `collapse` arguments to `str_c()`.*
`sep` puts characters between items within a vector, collapse puts a character between vectors being collapsed
1. *Use `str_length()` and `str_sub()` to extract the middle character from a string.*
```{r}
x <- "world"
str_sub(x, start = ceiling(str_length(x) / 2), end = ceiling(str_length(x) / 2))
```
*What will you do if the string has an even number of characters?*
In this circumstance the above solution would take the anterior middle value, below is a solution that would return both middle values.
```{r}
x <- "worlds"
str_sub(x, ceiling(str_length(x) / 2 + 1), start = ceiling(str_length(x) / 2 + 1))
str_sub(x,
start = ifelse(str_length(x) %% 2 == 0, floor(str_length(x) / 2), ceiling(str_length(x) / 2 )),
end = floor(str_length(x) / 2) + 1)
```
1. *What does `str_wrap()` do? When might you want to use it?*
* Use `indent` for first line, `exdent` for others
* could use `str_wrap()` for editing of documents etc., setting `width = 1` will give each word its own line
```{r}
str_wrap("Tonight, we dine in Hell.", width = 10, indent = 0, exdent = 3) %>%
writeLines()
```
1. *What does `str_trim()` do? What's the opposite of `str_trim()`?*
Removes whitespace from beginning and end of character, `side` argument specifies which side
```{r}
str_trim(" so much white space ", side = "right") # (default is 'both')
```
1. *Write a function that turns (e.g.) a vector `c("a", "b", "c")` into the string `a, b, and c`. Think carefully about what it should do if given a vector of length 0, 1, or 2.*
```{r}
vec_to_string <- function(x) {
#If 1 or 0 length vector
if (length(x) < 2)
return(x)
comma <- ifelse(length(x) > 2, ", ", " ")
b <- str_c(x, collapse = comma)
#replace ',' with 'and' in last
str_sub(b,-(str_length(x)[length(x)] + 1), -(str_length(x)[length(x)] +
1)) <- " and "
return(b)
}
x <- c("a", "b", "c", "d")
vec_to_string(x)
```
## 14.3: Matching patterns w/ regex
```{r}
x <- c("apple", "banana", "pear")
str_view(x, "an")
```
To match a literal `\` need `\\\\` because both string and regex will escape it.
```{r}
x <- "a\\b"
writeLines(x)
str_view(x,"\\\\")
```
Using `\b` to set boundary between words (not used often)
```{r}
apropos("\\bsum\\b")
apropos("^(sum)$")
```
Other special characters:
* `\d`: matches any digit.
* `\s`: matches any whitespace (e.g. space, tab, newline).
* `[abc]`: matches a, b, or c.
* `[^abc]`: matches anything except a, b, or c.
Controlling number of times:
* `?`: 0 or 1
* `+`: 1 or more
* `*`: 0 or more
* `{n}`: exactly n
* `{n,}`: n or more
* `{,m}`: at most m
* `{n,m}`: between n and m
By default these matches are "greedy": they will match the longest string possible. You can make them "lazy", matching the shortest string possible by putting a `?` after them. This is an advanced feature of regular expressions, but it's useful to know that it exists:
```{r}
x <- "1888 is the longest year in Roman numerals: MDCCCLXXXVIII"
str_view(x, 'C{2,3}')
str_view(x, 'C{2,3}?')
```
### 14.3.1.1
1. *Explain why each of these strings don't match a `\`: `"\"`, `"\\"`, `"\\\"`.*
`"\"` -> leaves open quote string because escapes quote
`"\\"`, -> escapes second `\` so left with blank
`"\\\"` -> third `\` escapes quote so left with open quote as well
1. *How would you match the sequence `"'\`?*
```{r}
x <- "alfred\"'\\goes"
writeLines(x)
str_view(x, "\\\"'\\\\")
```
1. *What patterns will the regular expression `\..\..\..` match?*
Would match 6 character string of following form "(dot)(anychar)(dot)(anychar)(dot)(anychar)"
```{r}
x <- c("alf.r.e.dd.ss..lsdf.d.kj")
str_view(x, pattern = "\\..\\..\\..")
```
*How would you represent it as a string?*
```{r}
x_pattern <- "\\..\\..\\.."
writeLines(x_pattern)
```
### 14.3.2.1
1. *How would you match the literal string `"$^$"`?*
```{r}
x <- "so it goes $^$ here"
str_view(x, "\\$\\^\\$")
```
1. *Given the corpus of common words in `stringr::words`, create regular expressions that find all words that:*
1. *Start with "y".*
```{r}
str_view(stringr::words, "^y", match = TRUE)
```
2. *End with "x"*
```{r}
str_view(stringr::words, "x$", match = TRUE)
```
3. *Are exactly three letters long. (Don't cheat by using `str_length()`!)*
```{r, eval = FALSE}
str_view(stringr::words, "^...$", match = TRUE)
```
4. *Have seven letters or more.*
```{r, eval = FALSE}
str_view(stringr::words, ".......", match = TRUE)
```
Since this list is long, you might want to use the `match` argument to `str_view()` to show only the matching or non-matching words.
### 14.3.3.1
1. *Create regular expressions to find all words that:*
1. *Start with a vowel.*
```{r, eval = FALSE}
str_view(stringr::words, "^[aeiou]", match = TRUE)
```
2. *That only contain consonants. (Hint: thinking about matching "not"-vowels.)*
```{r}
str_view(stringr::words, "^[^aeiou]*[^aeiouy]$", match = TRUE)
```
3. *End with `ed`, but not with `eed`.*
```{r}
str_view(stringr::words, "[^e]ed$", match = TRUE)
```
4. *End with `ing` or `ise`.*
```{r}
str_view(stringr::words, "(ing|ise)$", match = TRUE)
```
1. *Empirically verify the rule "i before e except after c".*
```{r}
str_view(stringr::words, "(^(ei))|cie|[^c]ei", match = TRUE)
```
1. *Is "q" always followed by a "u"?*
```{r}
str_view(stringr::words, "q[^u]", match = TRUE)
```
of the words in list, yes.
1. *Write a regular expression that matches a word if it's probably written in British English, not American English.*
```{r}
str_view(stringr::words, "(l|b)our|parat", match = TRUE)
```
1. *Create a regular expression that will match telephone numbers as commonly written in your country.*
```{r}
x <- c("dkl kls. klk. _", "(425) 591-6020", "her number is (581) 434-3242", "442", " dsi")
str_view(x, "\\(\\d\\d\\d\\)\\s\\d\\d\\d-\\d\\d\\d\\d")
```
Aboves not a good way to solve this, will see better methods in next section.
### 14.3.4.1
1. *Describe the equivalents of `?`, `+`, `*` in `{m,n}` form.*
`?` : `{0,1}`
`+` : `{1, }`
`*` : `{0, }`
1. *Describe in words what these regular expressions match: (read carefully to see if I'm using a regular expression or a string that defines a regular expression.)*
1. `^.*$` : starts with anything, and ends with anything--matches whole thing
```{r}
str_view(x, "^.*$")
```
2. `"\\{.+\\}"` : match text in brackets greater than nothing
```{r}
x <- c("test", "some in {brackets}", "just {} no match")
str_view(x, "\\{.+\\}")
```
3. `\d{4}-\d{2}-\d{2}`: 4 numbers - 2 numbers - 2 numbers
```{r}
x <- c("4444-22-22", "test", "333-4444-22")
str_view(x, "\\d{4}-\\d{2}-\\d{2}")
```
4. `"\\\\{4}"`: 4 brackets
```{r}
x <- c("\\\\\\\\", "\\\\\\", "\\\\", "\\")
writeLines(x)
str_view(x, "\\\\{4}")
x <- c("\\\\\\\\", "\\\\\\", "\\\\", "\\")
str_view(x, "\\\\\\\\")
```
1. *Create regular expressions to find all words that:*
1. find all words that start with three consonants
```{r}
str_view(stringr::words, "^[^aeoiouy]{3}", match = TRUE)
```
* Include `y` because when it shows up otherwise, is in vowel form.
2. have three or more vowels in a row
```{r}
str_view(stringr::words, "[aeiou]{3}", match = TRUE)
```
In this case, do not include the `y`.
3. have 2 or more vowel-consonant pairs in a row
```{r, eval = FALSE}
str_view(stringr::words, "([aeiou][^aeiou]){2,}", match = TRUE)
```
1. *Solve the beginner regexp crosswords at*
*<https://regexcrossword.com/challenges/beginner>.*
### 14.3.5.1
1. *Describe, in words, what these expressions will match:*
* I change questions 1 and 3 to what I think they were meant to be written as `(.)\\1\\1` and `(.)\\1` respectively.
1. `(.)\\1\\1` : repeat the char in the first group, and then repeat that char again
1. `"(.)(.)\\2\\1"` : 1st char, 2nd char followed by 2nd char, first char
1. `(..)\\1` : 2 chars repeated twice
1. `"(.).\\1.\\1"` : chars shows-up 3 times with one character between each
1. `"(.)(.)(.).*\\3\\2\\1"` : 3 chars in one order with * chars between, then 3 chars with 3 letters in the reverse order of what it started
```{r}
x <- c("steefddff", "ssdfsdfffsdasdlkd", "DLKKJIOWdkl", "klnlsd", "t11", "(.)\1\1")
str_view_all(x, "(.)\\1\\1", match = TRUE) #xxx
str_view_all(fruit, "(.)(.)\\2\\1", match = TRUE) #xyyx
str_view_all(fruit, "(..)\\1", match = TRUE) #xxyy
str_view(stringr::words, "(.).\\1.\\1", match = TRUE) #x.x.x
str_view(stringr::words, "(.)(.)(.).*\\3\\2\\1", match = TRUE) #xyz.*zyx
```
1. *Construct regular expressions to match words that:*
1. *Start and end with the same character.*
```{r, eval = FALSE}
str_view(stringr::words, "^(.).*\\1$", match = TRUE)
```
2. *Contain a repeated pair of letters*
(e.g. "church" contains "ch" repeated twice.)
```{r, eval = FALSE}
str_view(stringr::words, "(..).*\\1", match = TRUE)
```
3. *Contain one letter repeated in at least three places*
(e.g. "eleven" contains three "e"s.)
```{r, eval = FALSE}
str_view(stringr::words, "(.).+\\1.+\\1", match = TRUE)
```
## 14.4 Tools
```{r, eval = FALSE}
noun <- "(a|the) ([^ \\.]+)"
has_noun <- sentences %>%
str_subset(noun) %>%
head(10)
has_noun %>%
str_extract_all(noun, simplify = TRUE)
#creates split into seperate pieces
has_noun %>%
str_match_all(noun)
#Can make dataframe with, but need to name all
tibble(has_noun = has_noun) %>%
extract(has_noun, into = c("article", "noun"), regex = noun)
```
* When using `boundary()` with `str_split` can set to "character", "line", "sentence", and "word" and gives alternative to splitting by pattern.
### 14.4.2
1. *For each of the following challenges, try solving it by using both a single*
*regular expression, and a combination of multiple `str_detect()` calls.*
1. *Find all words that start or end with `x`.*
```{r}
str_subset(words, "^x|x$")
```
2. *Find all words that start with a vowel and end with a consonant.*
```{r}
str_subset(words, "^[aeiou].*[^aeiouy]$")
```
Counted `y` as a vowel if ending with, but not to start. This does not work perfect. For example words like `ygritte` would still be included even though `y` is activng as a vowel there whereas words like `boy` would be excluded even though acting as a consonant there. From here on out I am going to always exclude `y`.
3. *Are there any words that contain at least one of each different vowel?*
```{r}
vowels <- c("a","e","i","o","u")
words[str_detect(words, "a") &
str_detect(words, "e") &
str_detect(words, "i") &
str_detect(words, "o") &
str_detect(words, "u")]
```
No.
1. *What word has the highest number of vowels? What word has the highest*
*proportion of vowels? (Hint: what is the denominator?)*
```{r}
vowel_counts <- tibble(words = words,
n_string = str_length(words),
n_vowel = str_count(words, vowels),
prop_vowel = n_vowel / n_string)
```
'Experience' has the most vowels
```{r}
vowel_counts %>%
arrange(desc(n_vowel))
```
'a' has the highest proportion
```{r}
vowel_counts %>%
arrange(desc(prop_vowel))
```
### 14.4.3.1
1. *In the previous example, you might have noticed that the regular*
*expression matched "flickered", which is not a colour. Modify the *
*regex to fix the problem.*
Add space in front of colors:
```{r}
colours <- c("red", "orange", "yellow", "green", "blue", "purple") %>%
paste0(" ", .)
colour_match <- str_c(colours, collapse = "|")
more <- sentences[str_count(sentences, colour_match) > 1]
str_view_all(more, colour_match)
```
1. *From the Harvard sentences data, extract:*
1. *The first word from each sentence.*
```{r, eval = FALSE}
str_extract(sentences, "[A-z]*")
```
2. *All words ending in `ing`.*
```{r, eval = FALSE}
#ends in "ing" or "ing."
sent_ing <- str_subset(sentences, ".*ing(\\.|\\s)")
str_extract_all(sent_ing, "[A-z]+ing", simplify=TRUE)
```
3. *All plurals.*
```{r, eval = FALSE}
str_subset(sentences, "[A-z]*s(\\.|\\s)") %>% #take all sentences that have a word ending in s
str_extract_all("[A-z]*s\\b", simplify = TRUE) %>%
.[str_length(.) > 3] %>% #get rid of the short words
str_subset(".*[^s]s$") %>% #get rid of words ending in 'ss'
str_subset(".*[^i]s$") #get rid of 'this'
```
### 14.4.4.1
1. *Find all words that come after a "number" like "one", "two", "three" etc.*
*Pull out both the number and the word.*
```{r}
#Create regex expression
nums <- c("one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
nums_c <- str_c(nums, collapse = "|")
# see stringr cheatsheet: "(?<![:alpha:])" means not preceded by
re <- str_c("(", "(?<![:alpha:])", "(", nums_c, "))", " ", "([^ \\.]+)",
sep = "")
sentences %>%
str_subset(regex(re, ignore_case = TRUE)) %>%
str_extract_all(regex(re, ignore_case = TRUE)) %>%
unlist() %>%
tibble::enframe(name = NULL) %>%
separate(col = "value",
into = c("num", "following"),
remove = FALSE)
```
* I'd initially appended `"\\b"` in front of each number to prevent things like "someone" being captured -- however this didn't work with cases where a sentence started with a number -- hence switched to using the *not preceded by* method in the [stringr cheatsheet](https://www.rstudio.com/resources/cheatsheets/).
1. *Find all contractions. Separate out the pieces before and after the *
*apostrophe.*
```{r}
#note the () facilitate the split with functions
contr <- "([^ \\.]+)'([^ \\.]*)"
sentences %>%
#note the improvement this word definition is to the above [^ ]+
str_subset(contr) %>%
str_match_all(contr)
```
### 14.4.5.1
1. *Replace all forward slashes in a string with backslashes.*
```{r}
x <- c("test/dklsk/")
str_replace_all(x, "/", "\\\\") %>%
writeLines()
```
1. *Implement a simple version of `str_to_lower()` using `replace_all()`.*
```{r}
x <- c("BIdklsKOS")
str_replace_all(x, "([A-Z])", tolower)
```
1. *Switch the first and last letters in `words`. Which of those strings*
*are still words?*
```{r, eval = FALSE}
str_replace(words, "(^.)(.*)(.$)", "\\3\\2\\1")
```
Any words that start and end with the same letter, e.g. 'treat', as well as a few other examples like, war --> raw .
### 14.4.6.1
1. *Split up a string like `"apples, pears, and bananas"` into individual*
*components.*
```{r}
x <- "apples, pears, and bananas"
str_split(x, ",* ") #note that regular expression works to handle commas as well
```
1. *Why is it better to split up by `boundary("word")` than `" "`?*
Handles commas and punctuation^[I still sometimes prefer to use patterns where possible over `boundary` function. Regex is more generally applicabale as well outside of R.].
```{r}
str_split(x, boundary("word"))
```
1. *What does splitting with an empty string (`""`) do? Experiment, and*
*then read the documentation.*
Splitting by an empty string splits up each character.
```{r}
str_split(x,"")
```
* splits each character into an individual element (and creates elements for spaces between strings)
## 14.5: Other types of patterns
`regex` args to know:
* `ignore_case = TRUE` allows characters to match either their uppercase or
lowercase forms. This always uses the current locale.
* `multiline = TRUE` allows `^` and `$` to match the start and end of each
line rather than the start and end of the complete string.
* `comments = TRUE` allows you to use comments and white space to make
complex regular expressions more understandable. Spaces are ignored, as is
everything after `#`. To match a literal space, you'll need to escape it:
`"\\ "`.
* `dotall = TRUE` allows `.` to match everything, including `\n`.
Alternatives to `regex()`:
* `fixed()`: matches exactly the specified sequence of bytes. It ignores
all special regular expressions and operates at a very low level.
This allows you to avoid complex escaping and can be much faster than
regular expressions.
* `coll()`: compare strings using standard **coll**ation rules. This is
useful for doing case insensitive matching. Note that `coll()` takes a
`locale` parameter that controls which rules are used for comparing
characters.
### 14.5.1
1. *How would you find all strings containing `\` with `regex()` vs.*
*with `fixed()`?*
would be `\\` instead of `\\\\`
```{r}
str_view_all("so \\ the party is on\\ right?", fixed("\\"))
```
1. *What are the five most common words in `sentences`?*
```{r}
str_extract_all(sentences, boundary("word"), simplify = TRUE) %>%
as_tibble() %>%
gather(V1:V12, value = "words", key = "order") %>%
mutate(words = str_to_lower(words)) %>%
filter(!words == "") %>%
count(words, sort = TRUE) %>%
head(5)
```
## 14.7: stringi
Other functions:
* `apropos` searches all objects available from the global environment--useful if you can't remember fun name.
Check those that start with `replace`:
```{r}
apropos("^(replace)")
```
Check those that start with `str`, but not `stri`
```{r}
apropos("^(str)[^i]")
```
### 14.7.1
1. *Find the stringi functions that:*
1. *Count the number of words.* -- `stri_count`
2. *Find duplicated strings.* -- `stri_duplicated`
3. *Generate random text.* -- `str_rand_strings`
1. *How do you control the language that `stri_sort()` uses for sorting?*
The `decreasing` argument
## Appendix
### 14.4.2.3
One way of doing this using iteration methods:
```{r}
vowels <- c("a","e","i","o","u")
tibble(vowels = vowels, words = list(words)) %>%
mutate(detect_vowels = purrr::map2(words, vowels, str_detect)) %>%
spread(key = vowels, value = detect_vowels) %>%
unnest() %>%
mutate(unique_vowels = rowSums(.[2:6])) %>%
arrange(desc(unique_vowels))
#seems that nothing gets over 4
```