LoginSignup
15
16

More than 5 years have passed since last update.

R言語 - データ検証パッケージ "validate"

Last updated at Posted at 2016-08-10

はじめに

validate パッケージ を使うと、データ検証作業の効率を向上させることができます。たとえば、指定したルールに従って、ルールに合格したか、評価に失敗したか、などを検証できます。

データの構造をチェックする

▼サンプルスクリプト

R
# 環境情報
# R version 3.2.5 (2016-04-14)  -- Very, Very Secure Dishes 
# パッケージのインストール
install.packages( "magrittr" )
install.packages( "validate" )
install.packages( "yaml" )

# ライブラリの読み込み
library( magrittr )
library( validate )
library( yaml )

# データの構造をチェックする
iris %>% check_that(
  Sepal.Width > 0.5 * Sepal.Length                          # V1
  , mean( Sepal.Width ) > 0                                 # V2
  , sd( Sepal.Width ) < 0                                   # V3
  , if ( Sepal.Width > 0.5*Sepal.Length ) Sepal.Length > 10 # V4
) %>% summary()

上記のサンプルスクリプトでは、summary() によって、check_that()の実行結果を表示しています。たとえば、ルール名「V2」では、Sepal.Width列全体の平均値が0よりい大きいことを検証しています。passes = "1",fails = "0" であることから、ルールに合格している事が分かります。

▼実行結果例

実行結果例
# check_thatの実行結果
  rule items passes fails nNA error warning                                              expression
1   V1   150     66    84   0 FALSE   FALSE                        Sepal.Width > 0.5 * Sepal.Length
2   V2     1      1     0   0 FALSE   FALSE                                   mean(Sepal.Width) > 0
3   V3     1      0     1   0 FALSE   FALSE                                     sd(Sepal.Width) < 0
4   V4   150     84    66   0 FALSE   FALSE !(Sepal.Width > 0.5 * Sepal.Length) | Sepal.Length > 10

データ検証ルールの定義

validator()は、オブジェクトに対するデータ検証ルールを定義できます。定義したオブジェクトは、バリデータオブジェクトと呼ばれ、データ検証ルールとして再利用できます。
▼サンプルスクリプト

R
v <-  validator(
  ratio = Sepal.Width > 0.5 * Sepal.Length
  , mean = mean( Sepal.Width ) > 0
  , sd = sd( Sepal.Width ) < 0
  , cnd = if ( Sepal.Width > 0.5*Sepal.Length ) Sepal.Length > 10
  )

▼実行結果例

実行結果例
v
# v(バリデータオブジェクト)の中身の確認
Object of class 'validator' with 4 elements:
 ratio: Sepal.Width > 0.5 * Sepal.Length
 mean : mean(Sepal.Width) > 0
 sd   : sd(Sepal.Width) < 0
 cnd  : !(Sepal.Width > 0.5 * Sepal.Length) | Sepal.Length > 10

次のサンプルスクリプトでは、このバリデータオブジェクトを使ってirisデータセットをconfront()で検証しています。
▼サンプルスクリプト

R
cf <- confront(iris, v)

▼実行結果例

実行結果例
cf
# cf(検証結果)の中身の確認
Object of class 'validation'
Call:
    confront(x = iris, dat = v)

Confrontations: 4
With fails    : 3
Warnings      : 0
Errors        : 0
# cf(検証結果)を棒グラフにして可視化します。
barplot( cf, main="iris" )

image

リファレンス

https://cran.r-project.org/web/packages/validate/vignettes/intro.html
https://cran.r-project.org/web/packages/validate/vignettes/rule-files.html

15
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
16