-
Notifications
You must be signed in to change notification settings - Fork 1
/
L7-strings.Rmd
509 lines (389 loc) · 15.2 KB
/
L7-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
---
title: "Strings"
output: html_document
---
```{r setup, echo=FALSE, message=FALSE, warning=FALSE}
rm(list=objects()) # start with a clean workspace
source("knitr_setup.R")
library(stringr)
```
> ### Learning Objectives
>
> * Understand basic functions in the `stringr` library for working with character data.
> * Understand how to deal with whitespace.
> * Understand how to split strings.
> * Understand how to match strings.
>
> ### Suggested readings
>
> * [Chapter 14](https://r4ds.had.co.nz/strings.html) of "R for Data Science", by Garrett Grolemund and Hadley Wickham
> * [Introduction to `stringr` vignette](https://cran.r-project.org/web/packages/stringr/vignettes/stringr.html)
> * The [`stringr` package documentation](https://stringr.tidyverse.org/)
---
A "string" is the generic word for character type variables. Base R has many built-in functions for working with strings, but they are often difficult to remember and unintuitive to use. Fortunately, the wonderful folks over at the [tidyverse](https://www.tidyverse.org/) developed a lovely package called [`"stringr"`](https://stringr.tidyverse.org/), which makes working with strings a lot nicer.
Before going any further, make sure you install the `stringr` package and load it before trying to use any of the functions in this lesson:
```{r eval=FALSE}
install.packages("stringr")
library(stringr)
```
---
# Making a string
You can create strings with either single quotes (`''`) or double quotes (`""`). There is no difference in behavior.
```{r}
cat("This is a string")
cat('This is a string')
```
If you have a string that contains a `'` symbol, use double quotes:
Use them where it makes sense, e.g.:
```{r}
cat("It's a boy!")
```
Likewise, if you have a string that contains a `"` symbol, use single quotes:
Use them where it makes sense, e.g.:
```{r}
cat('I said, "Hi!"')
```
But what if you have a string that has both single and double quotes, like this: `It's nice to say, "Hi!"`
In this case, you have to "escape" the quotes by using the `\` symbol:
```{r}
cat("It's nice to say, \"Hi!\"") # Double quotes escaped
cat('It\'s nice to say, "Hi!"') # Single quote escaped
```
Escaping can be used for a lot of different string literals, such as starting a new line, adding a tab space, and even entering the `\` symbol itself:
```{r}
cat('New line:', 'This\nthat')
cat('Tab space:', 'This\tthat')
cat('Backslash:', 'This\\that')
```
Beware that the printed representation of a string in the R console is not the same as string itself, because the printed representation shows the escapes. To see the raw contents of the string, use `cat()` or `writeLines()`.
# String constants
R has a small number of built-in string constants: `LETTERS`, `letters`, `month.abb`, and `month.name`. These are common values stored in variables with convenient names:
```{r}
LETTERS
letters
month.abb
month.name
```
If you assign-over one of these constants, you can always retrieve the constant by putting the `base::` prefix in front:
```{r}
letters <- 7
letters
letters <- base::letters
letters
```
In addition to the Base R constants, the `stringr` library also comes with three constants: `words`, `sentences`, and `fruit`. These are much longer, so let's use the `head()` function to just preview the first 6 elements in each:
```{r}
head(words)
head(sentences)
head(fruit)
```
# Basic `"stringr"` Operations
Most `stringr` functions start with `str_`, which makes it particularly easy to remember. The following table contains the main `stringr` functions we'll cover:
|Function | Description |
|:----------------|:----------------------------------------|
|`str_to_lower()` | converts string to lower case |
|`str_to_upper()` | converts string to upper case |
|`str_to_title()` | converts string to title case |
|`str_length()` | number of characters |
|`str_sub()` | extracts substrings |
|`str_locate()` | returns indices of substrings |
|`str_dup()` | duplicates characters |
|`str_trim()` | removes leading and trailing whitespace |
|`str_pad()` | pads a string |
|`str_c()` | string concatenation |
|`str_split()` | split a string into a vector |
|`str_sort()` | sort a string alphabetically |
|`str_order()` | get the order of a sorted string |
|`str_detect()` | match a string in another string |
|`str_replace()` | replace a string in another string |
The common `str_` prefix is particularly useful in RStudio, because typing `str_` will trigger autocomplete, allowing you to see all `stringr` functions:
![](images/stringr-autocomplete.png){ width=600 }
## Case conversion
You can convert whole strings to lower-case, upper-case, and title-case using some conveniently-named functions:
```{r}
x <- "Want to hear a joke about paper? Never mind, it's tearable."
```
```{r}
str_to_lower(x)
str_to_upper(x)
str_to_title(x)
```
**Sidenote**: Notice that `str_to_title()` makes every first letter in each word upper case. This is slightly different from what you might expect, since most "titles" don't make articles like "a" and "the" upper case. An alternative function that makes a more appropriate title case is the `toTitleCase()` function from the **tools** library:
```{r}
library(tools)
toTitleCase(x)
```
## Get the number of characters in a string
If you want to find how long a string is (i.e. how many characters it contains), the `length()` function won't work:
```{r}
length("hello world")
```
That's be `length()` returns how many elements are in a _vector_ (in the above case, there's just one element). Instead, you should use `str_length()`:
```{r}
str_length("hello world")
```
Note that the space character has a length:
```{r}
str_length(" ")
```
Also note that the "empty" string (`""`) has no length:
```{r}
str_length("")
```
## Access characters by their index
You can access individual character using `str_sub()`. It takes three arguments: a string (or character vector), a `start` position, and an `end` position. Either position can either be a positive integer, which counts from the left, or a negative integer which counts from the right. The positions are inclusive, and if longer than the string, will be silently truncated.
```{r}
x <- "Apple"
str_sub(x, 1, 3)
# Negative numbers count backwards from the end
str_sub(x, -3, -1)
```
Note that `str_sub()` won't fail if the string is too short: it will just return as much as possible:
```{r}
str_sub("Apple", 1, 10)
```
You can also use the assignment form of `str_sub()` to modify specific elements in strings:
```{r}
x <- 'abcdef'
str_sub(x, 1, 3) <- 'ABC'
x
```
## Get the indices of substrings
If you want to know the start and end indices of a particular substring, use `str_locate()`. This is a helpful function to use in combination with `str_sub()` so you don't have to count the characters to find a substring.
For example, let's say I want to extract the substring `"Good"` from the following string:
```{r}
x <- 'thisIsGoodPractice'
```
I could first use `str_locate()` to get the start and end indices:
```{r}
indices <- str_locate(x, 'Good')
indices
```
Now that I have the start and end locations, I can use them within `str_sub()`:
```{r}
str_sub(x, indices[1], indices[2])
```
## Repeat a string
To duplicate strings, use `str_dup()`:
```{r}
str_dup("hola", 3)
```
Note the difference with `rep()` (which returns a vector):
```{r}
rep("hola", 3)
```
## Removing "whitespace"
`str_trim()` removes leading and trailing whitespace:
```{r}
x <- " aStringWithSpace "
x
str_trim(x)
```
By default, `str_trim()` removes whitespace on both sides, but you can specify a single side:
```{r}
str_trim(x, side = "left") # Only trim left side
str_trim(x, side = "right") # Only trim right side
```
## Add whitespace (or other characters)
`str_pad()` pads a string to a fixed length by adding extra whitespace on
the left, right, or both sides. Note that the `width` argument is the length of the _final_ string (not the length of the added padding):
```{r}
x <- "hello"
x
str_pad(x, width = 10) # Inserts pad on left by default
str_pad(x, width = 10, side = "both") # Pad both sides
```
You can pad with other characters by using the `pad` argument:
```{r}
str_pad(x, 10, side="both", pad='-')
```
Also, `str_pad()` will never make a string shorter:
```{r}
str_pad(x, 4)
```
## Combine strings into one string
To combine two or more strings, use `str_c()`:
```{r}
str_c('x', 'y', 'z')
```
Use the `sep` argument to control how they're separated:
```{r}
str_c('x', 'y', 'z', sep = "-")
```
You can also concatenate a _vector_ of strings by adding the `collapse` argument to the `str_c()` function:
```{r}
str_c(letters)
str_c(letters, collapse = '')
str_c(letters, collapse = '-')
```
Objects of length `0` are silently dropped. This is particularly useful in conjunction with `if` statements:
```{r}
printGreeting <- function(name, timeOfDay, isBirthday) {
greeting <- str_c(
"Good ", timeOfDay, " ", name,
if (isBirthday) {
", and HAPPY BIRTHDAY!"
} else {
'.'
}
)
cat(greeting)
}
```
```{r}
printGreeting('John', 'morning', isBirthday = FALSE)
printGreeting('John', 'morning', isBirthday = TRUE)
```
## Split a string into multiple strings
Use `str_split()` to split a string up into pieces along a particular delimiter.
```{r}
string <- 'This string has spaces-and-dashes'
```
```{r}
str_split(string, " ") # Split on the spaces
```
```{r}
str_split(string, "-") # Split on the dashes
```
By default, `str_split()` returns a `list` (another R data structure) of vectors. Each item in the list is a vector of strings. In the above cases, we gave `str_split()` a single string, so there is only one item in the returned list. In these cases, the easiest way to access the resulting vector of split strings is to use the double bracket `[[]]` operator to access the first list item:
```{r}
str_split(string, " ") # Returns a list of vectors
str_split(string, " ")[[1]] # Returns the first vector in the list
```
If you give `str_split()` a vector of strings, it will return a list of length equal to the number of elements in the vector:
```{r}
x <- c('babble', 'scrabblebabble')
str_split(x, 'bb') # Returns a list with two elements (each a vector)
```
A particularly useful string split is to split on the empty string (`""`), which breaks a string up into its individual characters:
```{r}
str_split(string, "")[[1]]
```
## Word extraction with `word()`
The `word()` function that another way to split up a longer string. It is designed to extract words from a sentence. You use `word()` by by passing it a `string` together with a `start` position of the first word to extract and an `end` position of the last word to extract. By default, the separator `sep` used between words is a single space. Here's some examples:
```{r}
sentence <- c("Be the change you want to be")
```
```{r}
# Extract first word
word(sentence, 1)
# Extract second word
word(sentence, 2)
# Extract last word
word(sentence, -1)
# Extract all but the first word
word(sentence, 2, -1)
```
## Alphabetically sorting string vectors
You can sort a vector of strings alphabetically using `str_sort()` and `str_order()`:
```{r}
x <- c('Y', 'M', 'C', 'A')
```
```{r}
str_sort(x)
str_sort(x, decreasing = TRUE)
str_order(x)
x[str_order(x)]
```
## Detect if a pattern is in a string
To determine if a character vector matches a pattern, use `str_detect()`. It returns a logical vector the same length as the input:
```{r}
tenFruit <- fruit[1:10]
tenFruit
str_detect(tenFruit, "berry")
```
Remember that when you use a logical vector in a numeric context, `FALSE` becomes `0` and `TRUE` becomes `1`. That makes `sum()` and `mean()` useful if you want to answer questions about matches across a vector:
```{r}
# How many fruit in tenFruit contain the string "berry"?
# How many words in the stringr "words" vector contain the letter "a"?
sum(str_detect(tenFruit, "berry"))
# What proportion contain the string "berry"?
mean(str_detect(tenFruit, "berry"))
```
If you want to _count_ the number of times a particular string pattern appears, use `str_count`:
```{r}
x <- c("apple", "banana", "pear")
str_count(x, "a")
```
## Anchors
By default, `str_detect()` will match any part of a string. But it's often useful to _anchor_ the matching condition so that it matches from the start or end of the string. You can use:
- `^` to match the _start_ of the string.
- `$` to match the _end_ of the string.
```{r}
# Which fruit start with "a"?
str_detect(tenFruit, "^a")
# Which fruit end with "y"?
str_detect(tenFruit, "e$")
```
To remember which is which, try this mnemonic:
> If you _start_ with power (`^`), you'll _end_ up with money (`$`).
To force a match to a complete string, anchor it with both `^` and `$`:
```{r}
x <- c("apple pie", "apple", "apple cake")
```
```{r}
str_detect(x, "apple")
str_detect(x, "^apple$")
```
In the second example above, 1 & 3 are `FALSE` because there's a space after `apple`.
## Replacing matched pattern with another string
`str_replace()` and `str_replace_all()` allow you to replace matches with new strings. The simplest use is to replace a pattern with a fixed string:
```{r}
x <- c("apple", "pear", "banana")
```
```{r}
str_replace(x, "a", "-")
str_replace_all(x, "a", "-")
```
# `stringr` functions work on vectors
In many of the above examples, we used a single string, but most `stringr` functions are designed to work on vectors of strings. For example, consider a vector of two "fruit":
```{r}
x <- c("apples", "oranges")
x
```
Get the first 3 letters in each string in `x`:
```{r}
str_sub(x, 1, 3)
```
Duplicate each string in `x` twice:
```{r}
str_dup(x, 2)
```
Convert all strings in `x` to upper case:
```{r}
str_to_upper(x)
```
Replace all `"a"` characters with a `"-"` character:
```{r}
str_replace_all(x, "a", "-")
```
# Tips
## Breaking a string into characters
Often times you'll want to break a string into it's individual character components. To do that, use `str_split()` with the empty string `""` as the delimiter:
```{r}
chars <- str_split("apples", "")[[1]]
chars
```
## Breaking a sentence into words
Similarly, if you have a single string that contains words separated by spaces, splitting on `" "` will break it into words:
```{r}
x <- "If you want to view paradise, simply look around and view it"
str_split(x, " ")[[1]]
```
## Comparing strings
If you want to compare whether two strings are the same, you must also consider their cases. For example:
```{r}
a <- "Apples"
b <- "apples"
a == b
```
The above returns `FALSE` because the cases are different on the `"a"` characters. If you want to ignore case, then a common strategy is to first convert the strings to a common case before comparing. For example:
```{r}
str_to_lower(a) == str_to_lower(b)
```
---
**Page sources**:
Some content on this page has been modified from other courses, including:
- [R for Data Science](https://r4ds.had.co.nz/strings.html), by Garrett Grolemund & Hadley Wickham
- [Handling Strings with R](https://www.gastonsanchez.com/r4strings/), by Gaston Sanchez
- [Introduction to `stringr` vignette](https://cran.r-project.org/web/packages/stringr/vignettes/stringr.html)