-
Notifications
You must be signed in to change notification settings - Fork 2
/
R06_strings.qmd
103 lines (57 loc) · 2.15 KB
/
R06_strings.qmd
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
# Strings
Modifying strings (i.e. text) is a very common task but can be a bit tricky if you start out.
Here are some functions to try out:
* create strings from multiple "substrings" with the `paste` or `paste0` function
```{r}
n = 5
paste("The number five:", n)
# again functions are vectorized
paste(seq(10), "is", c("odd", "even"))
# paste0 defaults to no character for separating the strings
paste0(n, "five", n)
```
## The stringr package
For advanced string handling we will make our lives easier by using the `stringr` package.
To use functions from a package we have to load it first with the `library` function. The first time you want to use a package you might have to install it first with `install.packages`.
```{r, include = FALSE}
library(stringr)
```
```{r, eval = FALSE}
install.packages("stringr")
library(stringr)
```
Many packages have so called `vignettes` which are tutorial style help pages about the package.
You can access vignettes via the "Packages" Pane in R studio or with a quick [Google search](https://www.google.com/search?q=stringr+vignette).
It is a good idea to go over the vignette when using a new package.
```{r}
s = "Hi Mom!"
# you can indicate in your script from which package a function comes from
# by using ::
stringr::str_length(s)
str_sub(string = s, start = 1, end = 2)
# vectorized:
string_vector = paste(seq(12), "is", c("odd", "even"))
string_vector
str_remove(string_vector, pattern = "is ")
# stringr functions are part of the tidyverse
# pipes work:
string_vector |> str_replace(pattern = " is", replacement = ":")
```
### Pattern matching
Pattern matching are logical operators for strings.
```{r}
str_detect(string_vector, pattern = "odd")
str_which(string_vector, pattern = "even")
str_starts(string_vector, pattern = "1")
str_count(string_vector, pattern = "1")
```
### Leading Zeros
`str_pad` one can be quite important to keep you sane.
```{r}
string_vector = paste(seq(15), "is", c("odd", "even"))
string_vector
string_vector_pad = paste(str_pad(seq(15), width = 2, pad = 0, side = "left"),
"is",
c("odd", "even"))
string_vector_pad
```