-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lab_5.Rmd
executable file
·427 lines (359 loc) · 13.2 KB
/
Lab_5.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
---
title: "5. Работа со строками"
output:
html_document:
theme: spacelab
highlight: pygments
toc: yes
toc_position: right
toc_depth: 4
toc_float: yes
smooth_scroll: false
df_print: paged
---
<style>
.parallax {
/* The image used */
background-image: url("5_strings.jpg");
/* Set a specific height */
min-height: 300px;
/* Create the parallax scrolling effect */
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: auto;
}
</style>
<div class="parallax"></div>
### 1. Как получить строку?[^1]
[^1]: Данная картинка -- рисунок Бориса Аркадьевича Диодорова из книжки Яна Экхольма "Тутта Карлссон, первая и единственная, Людвиг Четырнадцатый и другие"
* следите за кавычками
```{r}
"the quick brown fox jumps over the lazy dog"
'the quick brown fox jumps over the lazy dog'
"the quick 'brown' fox jumps over the lazy dog"
'the quick "brown" fox jumps over the lazy dog'
```
* пустая строка
```{r}
""
''
character(3)
```
* преобразование
```{r}
typeof(4:7)
as.character(4:7)
```
* встроенные векторы
```{r}
letters
LETTERS
month.name
```
* пользовательские данные
```{r}
str(data.frame(letters[6:10], LETTERS[4:8]))
str(data.frame(letters[6:10], LETTERS[4:8], stringsAsFactors = FALSE))
```
* `stringi`
```{r}
set.seed(42)
stringi::stri_rand_strings(n = 10, length = 5:14)
stringi::stri_rand_shuffle("любя, съешь щипцы, — вздохнёт мэр, — кайф жгуч")
stringi::stri_rand_shuffle(month.name[1:8]) # на больших векторах глючит
stringi::stri_rand_lipsum(nparagraphs = 2)
```
<div class="parallax"></div>
### 2. Операции со строками
* изменение регистра
* подсчет количества символов в строке
* сортировка строк
* соединение строк
* поиск вектора по подстроке
* разделение вектора по подстроке
* выделение подстроки по номеру
base R vs. `stringr`, `stringi`…
<div class="parallax"></div>
#### 2.1 Изменение регистра
```{r}
latin <- "tHe QuIcK BrOwN fOx JuMpS OvEr ThE lAzY dOg"
tolower(latin)
toupper(latin)
cyrillic <- "лЮбЯ, сЪеШь ЩиПцЫ, — вЗдОхНёТ мЭр, — кАйФ жГуЧ"
tolower(cyrillic)
toupper(cyrillic)
stringr::str_to_upper(latin)
stringr::str_to_lower(cyrillic)
stringr::str_to_title(latin)
```
<div class="parallax"></div>
#### 2.2 Подсчет количества символов
```{r}
nchar(latin)
nchar(month.name)
nchar(c(NULL, NA, ""))
stringr::str_length(latin)
stringr::str_length(month.name)
stringr::str_length(c(NULL, NA, ""))
```
<div class="parallax"></div>
#### 2.3 Сортировка
```{r}
unsorted_latin <- c("I", "♥", "N", "Y")
sort(unsorted_latin)
stringr::str_sort(unsorted_latin)
stringr::str_sort(unsorted_latin, locale = "lt")
unsorted_cyrillic <- c("я", "i", "ж")
stringr::str_sort(unsorted_cyrillic)
stringr::str_sort(unsorted_cyrillic, locale = "ru_UA")
sort(c(NULL, NA, ""))
stringr::str_sort(c(NULL, NA, ""))
```
Список локалей можно посмотреть командой `stringi::stri_locale_list()`. Еще полезные команды: `stringi::stri_locale_info` и `stringi::stri_locale_set`.
Не углубляясь в [разнообразие алгоритмов сортировки](https://www.youtube.com/watch?v=BeoCbJPuvSE), отмечу, что алгоритм по-умолчанию хуже работает с большими данными:
```{r, cache= TRUE}
set.seed(42)
huge <- sample(letters, 1e7, replace = TRUE)
head(huge)
system.time(
sort(huge)
)
system.time(
sort(huge, method = "radix")
)
system.time(
stringr::str_sort(huge)
)
huge_df <- data.frame(huge)
system.time(
dplyr::arrange(.data = huge_df, huge)
)
huge_tbl <- tibble::data_frame(huge)
system.time(
dplyr::arrange(.data = huge_tbl, huge)
)
```
Предварительный вывод: для больших данных -- `sort(..., method = "radix")`.
<div class="parallax"></div>
#### 2.4 Соединение
* одинаковое количество строк
```{r}
greek_abc <- c("Α", "Β", "Γ", "Δ")
latin_abc <- c("A", "B", "C", "D")
paste(greek_abc, latin_abc)
paste0(greek_abc, latin_abc)
paste(greek_abc, latin_abc, sep = "-")
paste(greek_abc, "Ы") # если векторы разной длины
```
* ... → одна строка
```{r}
paste(greek_abc, collapse = "_")
paste(greek_abc, latin_abc, collapse = "_")
paste(greek_abc, latin_abc, sep = "-", collapse = "_")
```
* `stringr`
```{r}
stringr::str_c(greek_abc, latin_abc)
stringr::str_c(greek_abc, latin_abc, sep = " ")
stringr::str_c(greek_abc, latin_abc, sep = "-")
stringr::str_c(greek_abc, collapse = "_")
stringr::str_c(greek_abc, latin_abc, collapse = "_")
stringr::str_c(greek_abc, latin_abc, sep = "-", collapse = "_")
```
* К сожалению, аргументы `sep` и `collapse` не векторизованы, так что если хочется использовать разные разделители, нужно использовать аргумент `separators`:
```{r}
stringr::str_c(greek_abc, separaters = c("-", "_"))
stringr::str_c(greek_abc, separaters = c("-", "_"), collapse = "")
stringr::str_c(greek_abc, latin_abc, separaters = c("-", "_"))
stringr::str_c(greek_abc, latin_abc, separaters = c("-", "_"), sep = "^")
stringr::str_c(greek_abc, latin_abc, separaters = c("-", "_"), collapse = "")
stringr::str_c(greek_abc, latin_abc, sep = "^", separaters = c("-", "_"), collapse = "")
```
* глюки
```{r}
paste(c(NULL, NA, ""))
stringr::str_c(c(NULL, NA, ""))
```
<div class="parallax"></div>
#### 2.5 Поиск строки по подстроке
```{r}
a <- c("the quick", "brown fox", "jumps", "over the lazy dog")
grep("the", a)
grep("the", a, value = TRUE)
grep("the", a, invert = TRUE)
grep("the", a, invert = TRUE, value = TRUE)
grepl("the", a)
stringr::str_which(a, "the")
stringr::str_subset(a, "the")
stringr::str_detect(a, "the")
stringr::str_view(a, "o")
stringr::str_view_all(a, "o")
stringr::str_locate(a, "o")
```
<div class="parallax"></div>
#### 2.6 Замена подстроки в строке
```{r}
b <- c("the quick brown fox", "jumps over the lazy dog")
sub("o", "_", b)
gsub("o", "_", b)
stringr::str_replace(b, "o", "_")
stringr::str_replace_all(b, "o", "_")
```
<div class="parallax"></div>
#### 2.7 Разделение вектора по подстроке
```{r}
b
strsplit(b, " ")
stringr::str_split(b, " ")
stringr::str_split(b, " ", simplify = TRUE)
```
<div class="parallax"></div>
#### 2.8 Выделение подстроки по номеру
```{r}
b
substring(b, 11, 15)
# с 5 по 9 и с 16 по 19
substring(b, c(5, 16), c(9, 19))
substring("а роза упала на лапу Азора", 1:26, 1:26)
substring("мат и тут и там", 1:15, 15:1)
stringr::str_sub(b, 11, 15)
stringr::str_sub(b, c(5, 16), c(9, 19))
stringr::str_sub("а роза упала на лапу Азора", 1:26, 1:26)
stringr::str_sub("мат и тут и там", 1:15, 15:1)
stringr::str_sub(b, -3, -1) # обратите внимание: нестандартное использование "-"
```
<div class="parallax"></div>
#### 2.9 Транслитерация строк
В пакете `stringi` сууществует достаточно много методов транслитераций строк, которые можно вывести командой `stri_trans_list()`. Вот пример использования некоторых из них:
```{r}
stringi::stri_trans_general("stringi", "latin-cyrillic")
stringi::stri_trans_general("сырники", "cyrillic-latin")
stringi::stri_trans_general("stringi", "latin-greek")
stringi::stri_trans_general("stringi", "latin-armenian")
```
<div class="parallax"></div>
#### 2.10 Подгонка количества символов
Для удобства представления, иногда удобно обрезать строки до фиксированного количества символов в строке:
```{r}
s <- "Это слишком длинная строка"
stringr::str_trunc(s, 20, "right")
stringr::str_trunc(s, 20, "left")
stringr::str_trunc(s, 20, "center")
```
Или наоборот подогнать к какому-то фиксированному количеству символов:
```{r}
w <- "коротковато"
stringr::str_pad(w, 20, "right")
stringr::str_pad(w, 20, "left")
stringr::str_pad(w, 20, "both")
```
<div class="parallax"></div>
### 3. Операции над векторами
Векторы не мноежества, но операции на них действуют те же:
* Объединение
* Пересечение
* Разность
* Сравнение
* Подмножество?
<div class="parallax"></div>
#### 3.1 Объединение
```{r}
a <- c("the quick", "brown fox", "jumps", "over the lazy dog")
b <- c("the quick", "brown fox", "jumps over the lazy dog")
c(a, b)
unique(c(a, b))
union(a, b)
```
<div class="parallax"></div>
#### 3.2 Пересечение
```{r}
a; b
intersect(a, b)
```
<div class="parallax"></div>
#### 3.3 Разность
```{r}
a; b
setdiff(a, b)
```
<div class="parallax"></div>
#### 3.4 Сравнение
```{r}
c <- c("brown fox", "jumps", "over the lazy dog", "the quick")
a; c
setequal(c, a)
identical(c, a)
```
<div class="parallax"></div>
#### 3.5 Подмножество?
```{r}
a
is.element("jumps", a)
is.element("the lazy dog", a)
is.element(c("jumps", "the lazy dog"), a)
c("jumps", "the lazy dog") %in% a
```
<div class="parallax"></div>
### 4. Задачи
#### 4.1 Чет-нечет
Напишите функцию `is.odd()`, которая возвращает значение `TRUE`, если число символов в строке нечетно, `FALSE`, если число символов в строке четно.
```{r,echo=FALSE, message = FALSE}
is.odd <- function(x){nchar(x) %% 2 == 1}
```
```{r}
is.odd(c("odd", "even", ""))
```
#### 4.2 Искусственные данные по средней продолжительности сна
[В данных по продолжительности сна](https://goo.gl/dpCSV2) (1.1_sleep_hours.csv)[^2] две переменных: код испытуемого и среднее время сна. Попробуйте сделать следующий график:
```{r, echo=FALSE, message = FALSE}
library(tidyverse)
read.csv("https://goo.gl/dpCSV2") %>%
mutate(sex = gsub("[0-9_]", "", code)) %>%
ggplot(aes(sleep_hours, fill = sex))+
geom_density(alpha= 0.4)+
theme_bw()+
labs(title = "Зависимость времени сна от пола",
caption = "искусственные данные",
y = "плотность",
x = "среднее время сна")
```
[^2]: Если у Вас не получается считать файл, попробуйте добавлять разные аргументы к `read.csv`: `encoding="UTF-8"` или `fileEncoding = "UTF-8"`… Я надеюсь, поможет…
#### 4.3 Алфавитный порядок
Как было сказано выше, "алфавитный" порядок разный в разных локалях. Напишите функцию `ordering_in_locales`, которая на вход принимает два символа, а возвращает таблицу с информацией о том, в скольких локалях порядок соответствует поданному в функцию, а в скольких порядок обратный:
```{r, echo=FALSE, message = FALSE}
ordering_in_locales <- function(x, y){
table(
sapply(stringi::stri_locale_list(), function(z){
paste(stringr::str_sort(c(x, y), locale = z), collapse = "_")}))}
```
```{r}
ordering_in_locales("i", "и")
```
#### 4.4 Функция для проверки полиндромности
Напишите функцию `is.palindrome`, которая будет проверять, является ли *слово* полиндромом.
```{r, echo=FALSE, message = FALSE}
is.palindrome <- function(x){
x <- gsub("\\W", "", tolower(x))
x == paste0(rev(substring(x, 1:nchar(x), 1:nchar(x))), collapse = "")
}
```
```{r}
is.palindrome("топот")
is.palindrome("топор")
```
#### 4.5 Функция для зеркального отражения размера букв
Напишите функцию `mirror_case()`, которая в строке все большие буквы заменяет на маленькие, а все маленькие -- на большие.
```{r, echo=FALSE, message = FALSE}
mirror_case <- function(x){
x <- substring(x, 1:nchar(x), 1:nchar(x))
lower <- tolower(x)
paste0(sapply(seq_along(x), function(i){
ifelse(x[i] == lower[i],
toupper(lower[i]), lower[i])}), collapse = "")
}
```
```{r}
mirror_case("ЖиЛи БыЛи ТрИ мЕдВеДя")
```
<div class="parallax"></div>