## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- library(zmisc) ## ----basics------------------------------------------------------------------- # The check returns its input, so it composes in a pipe c(2, 4, 6) |> chk_numeric(length = 3) |> sum() # On failure, the error names the argument as the caller wrote it my_mean <- function(x) { chk_numeric(x) sum(x) / length(x) } tryCatch(my_mean("seven"), error = wrap_error) ## ----params------------------------------------------------------------------- tryCatch(chk_character(c("a", NA), na.ok = FALSE), error = wrap_error) tryCatch(chk_integer(1:5, length = 3), error = wrap_error) tryCatch(chk_numeric(c(1, 99), range = c(0, 10)), error = wrap_error) tryCatch(chk_count(0, zero.ok = FALSE), error = wrap_error) ## ----pairs-------------------------------------------------------------------- chk_character(letters, length = c(10, NA)) |> length() chk_string("abc", range = c(1, 3)) |> nchar() ## ----attrs-------------------------------------------------------------------- labelled_ages <- structure(c(38L, 41L), label = "Age at interview") tryCatch(chk_integer(labelled_ages), error = wrap_error) chk_integer(labelled_ages, attr.ok = "label") |> sum() ## ----composite---------------------------------------------------------------- chk_data_frame(mtcars) |> nrow() chk_list(list(a = 1, b = 2), length = 2) |> names() # A data.frame is a list to typeof(), but not to chk_list() tryCatch(chk_list(mtcars), error = wrap_error) ## ----other-------------------------------------------------------------------- tryCatch(chk_class(1:3, "factor"), error = wrap_error) tryCatch(chk_true(nrow(mtcars) > 100), error = wrap_error) ## ----chk_that----------------------------------------------------------------- mtcars |> chk_that(nrow(.) > 10) |> ncol() tryCatch(mtcars |> chk_that(nrow(.) > 100), error = wrap_error) ## ----match-------------------------------------------------------------------- plot_kind <- function(kind = c("scatter", "line", "bar")) { kind <- chk_match(kind) kind } plot_kind() tryCatch(plot_kind("pie"), error = wrap_error) ## ----chk_any------------------------------------------------------------------ x <- "a" chk_any(chk_string(x), chk_number(x)) |> toupper() y <- TRUE tryCatch(chk_any(chk_string(y), chk_number(y)), error = wrap_error)