引数の確認

R関数入門

Richie Cotton

Data Evangelist at DataCamp

幾何平均

calc_geometric_mean <- function(x, na.rm = FALSE) {
  x %>%
    log() %>%
    mean(na.rm = na.rm) %>%
    exp()
}
calc_geometric_mean(letters)
Error in log(.) : 数学関数への非数値引数
R関数入門

数値かどうかの確認

calc_geometric_mean <- function(x, na.rm = FALSE) {

if(!is.numeric(x)) {
stop("x is not of class 'numeric'; it has class '", class(x), "'.")
}
x %>% log() %>% mean(na.rm = na.rm) %>% exp() }
Error in calc_geometric_mean(letters) : 
  x は 'numeric' クラスではありません。実際のクラスは 'character' です。
R関数入門

assertive でエラー処理を簡単に

テキスト付きの shutterstock_743531290.jpg

R関数入門

入力の型を確認

  • assert_is_numeric()
  • assert_is_character()
  • is_data.frame()
  • ...
  • is_two_sided_formula()
  • is_tskernel()
R関数入門

assertive で x をチェック

calc_geometric_mean <- function(x, na.rm = FALSE) {

assert_is_numeric(x)
x %>% log() %>% mean(na.rm = na.rm) %>% exp() }
 Error in calc_geometric_mean(letters) : 
  is_numeric : x は 'numeric' クラスではありません。実際のクラスは 'character' です。
R関数入門

x が正かを確認

calc_geometric_mean <- function(x, na.rm = FALSE) {
  assert_is_numeric(x)

assert_all_are_positive(x)
x %>% log() %>% mean(na.rm = na.rm) %>% exp() }
calc_geometric_mean(c(1, -1))
Error in calc_geometric_mean(c(1, -1)) :
  is_positive : x に非正の値が含まれています。
There was 1 failure:
  Position Value   Cause
1        2    -1 too low
R関数入門

is_* 関数

  • assert_is_numeric()
  • assert_all_are_positive()
  • is_numeric()(論理値を返す)
  • is_positive()(論理ベクトルを返す)
  • is_non_positive()
R関数入門

独自チェック

calc_geometric_mean <- function(x, na.rm = FALSE) {
  assert_is_numeric(x)

if(any(is_non_positive(x), na.rm = TRUE)) { stop("x contains non-positive values, so the geometric mean makes no sense.") }
x %>% log() %>% mean(na.rm = na.rm) %>% exp() }
calc_geometric_mean(c(1, -1))
Error in calc_geometric_mean(c(1, -1)) : 
  x に非正の値が含まれているため,幾何平均は意味をなしません。
R関数入門

入力の補正

use_first(c(1, 4, 9, 16))
[1] 1
Warning message:
c(1, 4, 9, 16) の最初の値(= 1)のみを使用します。
coerce_to(c(1, 4, 9, 16), "character")
[1] "1"  "4"  "9"  "16"
Warning message:
c(1, 4, 9, 16) をクラス ‘character’ に強制変換します。
R関数入門

na.rm の補正

calc_geometric_mean <- function(x, na.rm = FALSE) {
  assert_is_numeric(x)
  if(any(is_non_positive(x), na.rm = TRUE)) {
    stop("x contains non-positive values, so the geometric mean makes no sense.")
  }

na.rm <- coerce_to(use_first(na.rm), target_class = "logical")
x %>% log() %>% mean(na.rm = na.rm) %>% exp() }
calc_geometric_mean(1:5, na.rm = 1:5)
[1] 2.605171
Warning messages:
1: na.rm の最初の値(= 1)のみを使用します。 
2: use_first(na.rm) をクラス ‘logical’ に強制変換します。
R関数入門

練習しましょう!

R関数入門

Preparing Video For Download...