Схоже, що ці дані насправді мають всього 2 записи, проте у базу даних їх вносили різні люди або вони були зібрані з різних джерел інформації. Це досить поширена проблема у роботі з даними. Особливо коли відбуваєть заміна людей на рочих місцях або перехід на інше програмне забезпечення.
Якщо це буде розглядатися як факторна змінна без будь-якої попередньої обробки, очевидно, що 8, а не 2 класи будуть збережені. Тому завдання полягає в тому, щоб автоматично розпізнавати наведені вище дані про те, чи відноситься кожен елемент до чоловічої чи жіночої статі. У статистичних контекстах класифікацію таких “безладні” текстові рядки в ряд фіксованих категорій часто називають кодуванням.
Опишемо два взаємодоповнюючих підходи до кодування рядків: нормалізація (string normalization) рядків і аналіз схожості тексту (approximate text matching).
Розглянемо наступні підходи до очистки текстових даних:
- Видалення пробілів на початку або в кінці
- Обрізання/збільшення рядків до певної ширини
– Перетворення у верхній/нижній регістр.
– Пошук рядків, що містять прості шаблони (підрядки).
– Апроксимація рядків на основі "відстаней".
Робота з текстом у R здійснюється за допомогою пакету stringr.
Видалення пробілів на початку або в кінці здійснюється за допомогою функції str_trim().
library(stringr)str_trim(" ostroh academy ")str_trim(" ostroh academy ", side ="left")str_trim(" ostroh academy ", side ="right")
'ostroh academy'
'ostroh academy '
' ostroh academy'
Обрізання/збільшення рядків до певної ширини здійснюється за допомогою функції str_pad().
str_pad(57, width =6, side ="left", pad =0)
'000057'
str_pad("ostroh", width =10, side ="right", pad ="_")
'ostroh____'
Перетворення у верхній/нижній регістр
text <-"Ostroh Academy!"toupper(text)tolower(text)
'OSTROH ACADEMY!'
'ostroh academy!'
Пошук рядків, що містять прості шаблони (підрядки)
Скористаємося функцієя grep() та grepl() для пошуку підрядків у інформації про стать:
grepl("m", data$gender) # Повертає TRUE/FALSE, якщо знахоить входження рядкаgrep("m", data$gender) # Повертає номери рядків, по яких є входження
Your code contains a unicode char which cannot be displayed in your
current locale and R will silently convert it to an escaped form when the
R kernel executes this code. This can lead to subtle errors if you use
such chars to do comparisons. For more information, please see
https://github.com/IRkernel/repr/wiki/Problems-with-unicode-on-windows
FALSE
FALSE
TRUE
FALSE
TRUE
FALSE
TRUE
TRUE
FALSE
TRUE
FALSE
TRUE
TRUE
3
5
7
8
10
12
13
grepl("m", data$gender, ignore.case =TRUE) # не враховує регістр буквgrepl("m", tolower(data$gender))
Your code contains a unicode char which cannot be displayed in your
current locale and R will silently convert it to an escaped form when the
R kernel executes this code. This can lead to subtle errors if you use
such chars to do comparisons. For more information, please see
https://github.com/IRkernel/repr/wiki/Problems-with-unicode-on-windows
TRUE
TRUE
TRUE
TRUE
TRUE
FALSE
TRUE
TRUE
TRUE
TRUE
FALSE
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
FALSE
TRUE
TRUE
TRUE
TRUE
FALSE
TRUE
TRUE
data$gendergrepl("^m", data$gender, ignore.case =TRUE) # Показує усі збіги, що починаються з вказаної літери
Your code contains a unicode char which cannot be displayed in your
current locale and R will silently convert it to an escaped form when the
R kernel executes this code. This can lead to subtle errors if you use
such chars to do comparisons. For more information, please see
https://github.com/IRkernel/repr/wiki/Problems-with-unicode-on-windows
'Male'
' M'
'Female'
'Man'
'female'
'F '
'male.'
'm'
'Man'
'female'
'F '
'male.'
'm'
TRUE
FALSE
FALSE
TRUE
FALSE
FALSE
TRUE
TRUE
TRUE
FALSE
FALSE
TRUE
TRUE
Пошук “відстані” між ряжками - це аналіз рядків на схожіть з визначенням рівня співпадінь.
Your code contains a unicode char which cannot be displayed in your
current locale and R will silently convert it to an escaped form when the
R kernel executes this code. This can lead to subtle errors if you use
such chars to do comparisons. For more information, please see
https://github.com/IRkernel/repr/wiki/Problems-with-unicode-on-windows
A data.frame: 6 × 2
male
female
<dbl>
<dbl>
Male
0
2
X...M
3
5
Female
2
0
Man
2
4
F....
4
5
male.
1
3
Примінимо інформацію про відстані до “нечистих” даних про стать:
Your code contains a unicode char which cannot be displayed in your
current locale and R will silently convert it to an escaped form when the
R kernel executes this code. This can lead to subtle errors if you use
such chars to do comparisons. For more information, please see
https://github.com/IRkernel/repr/wiki/Problems-with-unicode-on-windows
Your code contains a unicode char which cannot be displayed in your
current locale and R will silently convert it to an escaped form when the
R kernel executes this code. This can lead to subtle errors if you use
such chars to do comparisons. For more information, please see
https://github.com/IRkernel/repr/wiki/Problems-with-unicode-on-windows
A data.frame: 13 × 2
initial
coded
<chr>
<chr>
Male
male
M
male
Female
female
Man
male
female
female
F
male
male.
male
m
male
Man
male
female
female
F
male
male.
male
m
male
Як альтернативу для знаходження відстаней між рядками можна використовувати функції з бібліотеки stringdist.
#install.packages("stringdist")
library(stringdist)adist("ao", "oa")stringdist("oa", "ao") # 1, а було 2
Your code contains a unicode char which cannot be displayed in your
current locale and R will silently convert it to an escaped form when the
R kernel executes this code. This can lead to subtle errors if you use
such chars to do comparisons. For more information, please see
https://github.com/IRkernel/repr/wiki/Problems-with-unicode-on-windows
A matrix: 1 × 1 of type dbl
2
1
Спробуємо “очистити” дані, які ми отримали з допомогою функції amatch():
Your code contains a unicode char which cannot be displayed in your
current locale and R will silently convert it to an escaped form when the
R kernel executes this code. This can lead to subtle errors if you use
such chars to do comparisons. For more information, please see
https://github.com/IRkernel/repr/wiki/Problems-with-unicode-on-windows
Your code contains a unicode char which cannot be displayed in your
current locale and R will silently convert it to an escaped form when the
R kernel executes this code. This can lead to subtle errors if you use
such chars to do comparisons. For more information, please see
https://github.com/IRkernel/repr/wiki/Problems-with-unicode-on-windows
Місія виконана! Замінимо та збережемо інформацію у файл для майбутніх експериментів по цій темі:
data <-read.csv("data/badtitled.csv")data <-clean_names(data)head(data, 2)
A data.frame: 2 × 5
person_age
person_height
person_weight
person_gender
empty
<int>
<chr>
<dbl>
<chr>
<lgl>
1
23
185
NA
Male
NA
2
41
175
68.3
M
NA
data <- data |>mutate(person_gender =ifelse(str_trim(person_gender) =="F", "female", person_gender))m <-c("male", "female")nums <-amatch(data$person_gender, m, maxDist =4)data <- data |>mutate(person_gender = m[nums])data
A data.frame: 13 × 5
person_age
person_height
person_weight
person_gender
empty
<int>
<chr>
<dbl>
<chr>
<lgl>
23
185
NA
male
NA
41
175
68.3
male
NA
11
142*
55.4
female
NA
12
NA
48.2
male
NA
54
191
NA
female
NA
32
168
78.0
female
NA
22
NA
54.0
male
NA
21
165
NA
male
NA
14
NA
90.2
male
NA
51
250
NA
female
NA
41
20
81.0
female
NA
66
NA
59.0
male
NA
71
171
NA
male
NA
Замінимо також висоту на числове значення, а не текст:
data <- data |>mutate(person_height =str_remove(data$person_height, pattern ="[*]"))data
A data.frame: 13 × 5
person_age
person_height
person_weight
person_gender
empty
<int>
<chr>
<dbl>
<chr>
<lgl>
23
185
NA
male
NA
41
175
68.3
male
NA
11
142
55.4
female
NA
12
NA
48.2
male
NA
54
191
NA
female
NA
32
168
78.0
female
NA
22
NA
54.0
male
NA
21
165
NA
male
NA
14
NA
90.2
male
NA
51
250
NA
female
NA
41
20
81.0
female
NA
66
NA
59.0
male
NA
71
171
NA
male
NA
data <- data |>mutate(person_height =as.numeric(person_height))data