范围约束

R 中的数据清洗

Maggie Matsui

Content Developer @ DataCamp

什么是越界值?

  • SAT 分数:400–1600
  • 包裹重量:至少 0 磅/千克
  • 成年人心率:60–100 次/分
R 中的数据清洗

查找越界值

movies
  title                 avg_rating
  <chr>                      <dbl>
1 A Beautiful Mind             4.1
2 La Vita e Bella              4.3
3 Amelie                       4.2
4 Meet the Parents             3.5
5 Unbreakable                  5.8
6 Gone in Sixty Seconds        3.3
...
R 中的数据清洗

查找越界值

breaks <- c(min(movies$avg_rating), 0, 5, max(movies$avg_rating))

ggplot(movies, aes(avg_rating)) + geom_histogram(breaks = breaks)

由代码生成的三箱直方图:过低箱有1个值,范围内有6个值,过高有2个值。

R 中的数据清洗

查找越界值

library(assertive)
assert_all_are_in_closed_range(movies$avg_rating, lower = 0, upper = 5)
Error: is_in_closed_range : movies$avg_rating are not all in the range [0,5].
There were 3 failures:
  Position Value    Cause
1        5   5.8 too high
2        8   6.2 too high
3        9  -4.4  too low
R 中的数据清洗

处理越界值

  • 删除行
  • 视为缺失值(NA
  • 替换为范围边界
  • 基于领域知识和/或数据集知识替换为其他值
R 中的数据清洗

删除行

movies %>%
  filter(avg_rating >= 0, avg_rating <= 5) %>%


ggplot(aes(avg_rating)) + geom_histogram(breaks = c(min(movies$avg_rating), 0, 5, max(movies$avg_rating)))

由代码生成的直方图:范围内有6个值,范围下方和上方均为0个。

R 中的数据清洗

视为缺失值

movies
  title                 avg_rating
  <chr>                      <dbl>
1 A Beautiful Mind             4.1
2 La Vita e Bella              4.3
3 Amelie                       4.2
4 Meet the Parents             3.5
5 Unbreakable                  5.8
6 Gone in Sixty Seconds        3.3
...

replace(col, condition, replacement)

movies %>%
  mutate(rating_miss = 
    replace(avg_rating, avg_rating > 5, NA))
  title                rating_miss
  <chr>                      <dbl>
1 A Beautiful Mind             4.1
2 La Vita e Bella              4.3
3 Amelie                       4.2
4 Meet the Parents             3.5
5 Unbreakable                   NA
6 Gone in Sixty Seconds        3.3
...
R 中的数据清洗

替换越界值

movies %>%
  mutate(rating_const = 
           replace(avg_rating, avg_rating > 5, 5))
  title               rating_const
  <chr>                      <dbl>
1 A Beautiful Mind             4.1
2 La Vita e Bella              4.3
3 Amelie                       4.2
4 Meet the Parents             3.5
5 Unbreakable                  5.0
6 Gone in Sixty Seconds        3.3
...
R 中的数据清洗

日期范围约束

assert_all_are_in_past(movies$date_recorded)
Error: is_in_past : movies$date_recorded are not all in the past.
There was 1 failure:
  Position               Value     Cause
1        3 2064-09-22 20:00:00 in future
library(lubridate)
movies %>%
  filter(date_recorded > today())
    title  avg_rating  date_recorded
1  Amelie         4.2  2064-09-23
R 中的数据清洗

删除越界日期

library(lubridate)
movies <- movies %>%
  filter(date_recorded <= today())
library(assertive)
assert_all_are_in_past(movies$date_recorded)


记住,无输出 = 通过!

R 中的数据清洗

Passons à la pratique !

R 中的数据清洗

Preparing Video For Download...