欠損値の検索と置換

Rでの欠損データの扱い方

Nicholas Tierney

Statistician

学習内容

  • 隠れた欠損値の探し方
  • 欠損値ラベルを NA に置換する方法
  • 欠損に関する前提の確認
Rでの欠損データの扱い方

欠損値の検索と置換

  • 理想的な形式 = NA
  • 欠損値が誤ってコーディングされることがある:例「missing」「Not Available」「N/A」
  • 欠損値が NA としてコーディングされていると仮定するのは誤り。
Rでの欠損データの扱い方

カオスデータの理解

score grade place
3 N/A -99
-99 E 97
4 missing 95
-99 na 92
7 n/a -98
10 missing
12 . 88
16 .
9 N/a 86

Rでの欠損データの扱い方

欠損値の検索

miss_scan_count()

chaos %>% miss_scan_count(search = list("N/A"))
# A tibble: 3 x 2
  Variable     n
  <chr>    <int>
1 score        0
2 grade        1
3 place        0
Rでの欠損データの扱い方

欠損値の検索

chaos %>%
  miss_scan_count(search = list("N/A",
                                "N/a"))
# A tibble: 3 x 2
  Variable     n
  <chr>    <int>
1 score        0
2 grade        2
3 place        0
Rでの欠損データの扱い方

欠損値の置換

chaos %>%
  replace_with_na(replace = list(grade = c("N/A", "N/a")))
# A tibble: 9 x 3
  score grade   place  
  <dbl> <chr>   <chr>  
1     3 NA      -99    
2   -99 E       97     
3     4 missing 95     
4   -99 na      92     
5     7 n/a     -98    
6    10 " "     missing
7    12 .       88     
8    16 ""      .      
9     9 NA      86
Rでの欠損データの扱い方

replace_with_na のスコープ付きバリアント

  • replace_with_na は繰り返しになりやすい:

    • 多くの変数・値に適用する場合
    • 複雑なケース(-1未満の値の置換、文字列列のみへの適用など)
  • replace_with_na_all() 全変数に適用。

  • replace_with_na_at() 指定した変数のサブセットに適用。
  • replace_with_na_if() 条件(数値型、文字型など)を満たす変数のサブセットに適用。
Rでの欠損データの扱い方

スコープ付きバリアントの使用

chaos %>%
  replace_with_na_all(condition = ~.x == -99)
# A tibble: 9 x 3
  score grade   place  
  <dbl> <chr>   <chr>  
1     3 N/A     NA     
2    NA E       97     
3     4 missing 95     
4    NA na      92     
5     7 n/a     -98    
6    10 " "     missing
7    12 .       88     
8    16 ""      .      
9     9 N/a     86
Rでの欠損データの扱い方

スコープ付きバリアントの使用

chaos %>% 
  replace_with_na_all(condition = ~.x %in% c("N/A", "missing", "na"))
# A tibble: 9 x 3
  score grade place
  <dbl> <chr> <chr>
1     3 NA    -99  
2   -99 E     97   
3     4 NA    95   
4   -99 NA    92   
5     7 n/a   -98  
6    10 " "   NA   
7    12 .     88   
8    16 ""    .    
9     9 N/a   86
Rでの欠損データの扱い方

練習しましょう!

Rでの欠損データの扱い方

Preparing Video For Download...