範圍限制

R 的資料清理

Maggie Matsui

Content Developer @ DataCamp

什麼是超出範圍的值?

  • SAT 分數:400–1600
  • 包裹重量:至少 0 lb/kg
  • 成人心率:每分鐘 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)

由程式碼產生的三欄長條圖:一筆過低、六筆在範圍內、兩筆過高。

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 的資料清理

一起來練習吧!

R 的資料清理

Preparing Video For Download...