### Install checkmate from CRAN Source: https://github.com/mllg/checkmate/blob/master/README.md Install the stable release of the checkmate package from CRAN. This is the recommended method for most users. ```r install.packages("checkmate") ``` -------------------------------- ### Install checkmate Development Version Source: https://github.com/mllg/checkmate/blob/master/README.md Install the development version of the checkmate package from GitHub using devtools. This is useful for accessing the latest features or bug fixes. ```r devtools::install_github("mllg/checkmate") ``` -------------------------------- ### Test Matrix Row Count Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Demonstrates an error when a matrix does not have the specified number of rows. ```r testMatrix(matrix(1:4, 2, 2), nrows = 3) # "Must have 3 rows, but has 2 rows" ``` -------------------------------- ### Test String Pattern Match Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Illustrates an error when a string does not match the specified regular expression pattern. ```r testString("test", pattern = "^[0-9]+$") # "Must comply to pattern '^[0-9]+$'" ``` -------------------------------- ### Test All Missing Values Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Illustrates an error when all values in a vector are missing and `all.missing = FALSE` is set. ```r testNumeric(c(1, 2, NA), all.missing = FALSE) # "All values are missing" ``` -------------------------------- ### Example of expect_* Function Usage Source: https://github.com/mllg/checkmate/blob/master/_autodocs/README.md Use expect_* functions within unit testing frameworks like testthat or tinytest. They return testthat/tinytest expectation objects. ```R expect_integer(result) ``` -------------------------------- ### Example of test* Function Usage Source: https://github.com/mllg/checkmate/blob/master/_autodocs/README.md Use test* functions for conditional logic without exceptions. They return TRUE on success and FALSE on failure. ```R if (testInteger(x)) { ... } ``` -------------------------------- ### Function Parameter Validation Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/scalar-checks.md Demonstrates how to use various assertion functions (assertInt, assertFlag, assertString) to validate parameters within a function, ensuring correct input types and values. ```r my_function <- function(x, verbose = FALSE, method = NULL) { assertInt(x, lower = 1) # x must be positive integer assertFlag(verbose) # verbose must be TRUE/FALSE assertString(method, choices = c("fast", "slow")) } ``` -------------------------------- ### Verbose Testing Output Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Demonstrates how to perform a test and provide user feedback based on the boolean result. If the test fails, it suggests using a check function to get more details. ```r # Test and show result success <- testInteger(x, lower = 0) if (success) { cat("Valid!\n") } else { cat("Invalid: use checkInteger() to see why\n") } ``` -------------------------------- ### Test Integer Lower Bound Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Illustrates an error when an integer value is below the specified lower bound. ```r testInt(-1, lower = 0) # "Must be >= 0, but is -1" ``` -------------------------------- ### Test DataFrame Column Count Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Illustrates an error when a data frame does not have the specified number of columns. ```r testDataFrame(iris, ncols = 10) # "Must have 10 columns, but has 5 columns" ``` -------------------------------- ### Check Integer Length Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Demonstrates an error message when an integer vector has an incorrect length. ```r checkInt(1:3) # "Must have length 1, but has length 3" ``` -------------------------------- ### Example of assert* Function Usage Source: https://github.com/mllg/checkmate/blob/master/_autodocs/README.md Use assert* functions for argument validation and immediate error reporting. They invisibly return the input on success and throw an error or collect it in an AssertCollection on failure. ```R assertInteger(x, .var.name = "count") ``` -------------------------------- ### Check Integer Type Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Demonstrates an error message when an integer check fails due to a double input. ```r checkInteger(1.5) # "Must be of type 'integer', but is 'double'" ``` -------------------------------- ### Conditional Logic with Test Functions Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Example of using `testInteger` and `testNumeric` for conditional branching in function logic, allowing different handling based on input type. ```r function(x) { if (testInteger(x)) { # Handle integer case return(x) } else if (testNumeric(x)) { # Handle numeric case return(as.integer(round(x))) } else { stop("x must be numeric") } } ``` -------------------------------- ### Test Choice Membership Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Demonstrates an error when a value is not found within the allowed set of choices. ```r testChoice("maybe", c("yes", "no")) # "Must be element of set {'yes','no'}, but is 'maybe'" ``` -------------------------------- ### Coalesce in Function Context Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/framework.md Provides an example of using the %??% operator within a function to assign a default value to a parameter if it is not explicitly provided. ```R function(x = NULL) { x <- x %??% get_default() # Use provided x or get default } ``` -------------------------------- ### Test Set Equality Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Shows an error when two sets are not equal, indicating missing elements in one set compared to the other. ```r testSetEqual(c(1, 2), c(1, 2, 3)) # "Must be set equal to {1,2,3}, but is missing elements {3}" ``` -------------------------------- ### Test Integer Length Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Illustrates an error message when an integer vector's length does not match the specified length. ```r testInteger(1:5, len = 3) # "Must have length 3, but has length 5" ``` -------------------------------- ### Test Character Exact Length Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Demonstrates an error when character elements do not have the exact specified number of characters. ```r testCharacter("hello", n.chars = 3) # "Each element must have exactly 3 characters" ``` -------------------------------- ### Test Missing Values Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Demonstrates an error when a vector contains missing values (NA) and `any.missing = FALSE` is set. ```r testInteger(c(1, NA, 3), any.missing = FALSE) # "Contains missing values" ``` -------------------------------- ### Example of check* Function Usage Source: https://github.com/mllg/checkmate/blob/master/_autodocs/README.md Use check* functions for low-level validation where you need to inspect the result. They return TRUE on success or an error message string on failure. ```R result <- checkInteger(x) ``` -------------------------------- ### Test Character Minimum Length Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Shows an error when character elements do not meet the minimum character length requirement. ```r testCharacter("abc", min.chars = 5) # "Each element must have at least 5 characters" ``` -------------------------------- ### Test Character Length Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Shows an error message when character elements do not meet minimum or maximum length requirements. ```r testCharacter(letters, min.len = 30, max.len = 40) # "Must have length <= 40, but has length 26" ``` -------------------------------- ### Test List Missing Values (NULL) Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Shows an error when a list contains NULL elements and `any.missing = FALSE` is specified. ```r testList(list(1, NULL), any.missing = FALSE) # "Contains missing values (NULL elements)" ``` -------------------------------- ### Custom Error Messages with AssertCollection Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Example of using AssertCollection to gather multiple validation errors and provide custom context before stopping execution. ```r coll <- makeAssertCollection() assertInteger(args$n, lower = 1, add = coll) assertNumeric(args$alpha, lower = 0, upper = 1, add = coll) assertCharacter(args$method, add = coll) if (!coll$isEmpty()) { msgs <- coll$getMessages() cat("Validation failed:\n") cat(paste0(" - ", msgs, collapse = "\n")) stop("Invalid arguments") } ``` -------------------------------- ### Test Numeric Finite Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Shows an error when a numeric vector contains non-finite values (Inf, -Inf, NaN) and `finite = TRUE` is set. ```r testDouble(c(1, 2, 3), finite = TRUE) # "Must be finite" (if Inf present) ``` -------------------------------- ### Register Test Backend Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/utility-functions.md Selects the testing framework (testthat or tinytest) for expectation functions. This must be called before using expect_* functions and loads the specified package. ```r # Use testthat backend register_test_backend("testthat") # Use tinytest backend register_test_backend("tinytest") # Auto-detection (default) # Detects if tinytest in .packages(), otherwise uses testthat ``` -------------------------------- ### Check Path for Output Suitability Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/specialized-checks.md Verifies if a path is suitable for creating output files, checking parent directory writability and handling existing files based on the 'overwrite' flag. Can also enforce specific file extensions. ```R testPathForOutput("output.txt") ``` ```R testPathForOutput("output.txt", overwrite = TRUE) ``` ```R assertPathForOutput("results.csv", extension = "csv") ``` -------------------------------- ### Test Unnamed Vector Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Demonstrates an error when a vector is expected to be named but is not. ```r testNamed(1:3, type = "named") # "Must be named, but is unnamed" ``` -------------------------------- ### Programmatic Error Handling with tryCatch Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Demonstrates how to use `tryCatch` to catch and handle errors programmatically, specifically catching a `simpleError` generated by `checkmate`. ```r tryCatch( assertInteger("not_int"), error = function(e) { cat("Caught error:", conditionMessage(e), "\n") } ) ``` -------------------------------- ### Test Subset Membership Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Illustrates an error when a vector contains elements not present in the allowed subset. ```r testSubset(c("x", "y", "z"), c("a", "b", "c")) # "Must be a subset of {'a','b','c'}, but has additional elements {'x','y','z'}" ``` -------------------------------- ### Compact Quick Assertions Source: https://github.com/mllg/checkmate/blob/master/_autodocs/README.md Use qassert and qtest for concise rule-based validation. These functions allow defining complex validation rules using a compact syntax for types, lengths, and ranges. ```r qassert(ids, "I+[0,)") # Integer vector, all ≥ 0 qtest(prob, "N1[0,1]") # Numeric scalar in [0,1] ``` -------------------------------- ### Test Missing Required Names Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Shows an error when a named vector does not include all the names specified in `must.include`. ```r testNames(c(a = 1, b = 2), must.include = c("a", "c")) # "Must include names {'a','c'}, but is missing 'c'" ``` -------------------------------- ### Quick Assertion and Testing Source: https://github.com/mllg/checkmate/blob/master/_autodocs/configuration.md Applies rules defined in quick syntax to a vector. `.var.name` allows custom error messages. ```r qassert(x, rules, .var.name = NULL) qtest(x, rules) ``` -------------------------------- ### checkPathForOutput / assertPathForOutput / testPathForOutput / expect_path_for_output Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/specialized-checks.md Validates if a path is suitable for creating output files, considering writability, overwriting, and file extensions. ```APIDOC ## checkPathForOutput / assertPathForOutput / testPathForOutput / expect_path_for_output ### Description Validate that path is suitable for creating output files. This function checks if the parent directory exists and is writable, and handles conditions for overwriting existing files or enforcing specific file extensions. ### Signature ```r checkPathForOutput(x, overwrite = FALSE, extension = NULL) assertPathForOutput(x, overwrite = FALSE, extension = NULL, .var.name = vname(x), add = NULL) ``` ### Parameters #### Path Parameters - **x** (character(1)) - Required - Output path - **overwrite** (logical(1)) - Optional - Allow overwriting existing file? Defaults to FALSE. - **extension** (character) - Optional - Required file extension. Defaults to NULL. ### Behavior - Checks parent directory exists and is writable - If file exists: checks overwrite permission - Can enforce file extension ### Examples ```r # Path writable, no file exists yet testPathForOutput("output.txt") # Overwrite existing file testPathForOutput("output.txt", overwrite = TRUE) # Check extension and writeability assertPathForOutput("results.csv", extension = "csv") ``` ``` -------------------------------- ### Test Numeric Upper Bound Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Demonstrates an error when a numeric value exceeds the specified upper bound. ```r testNumber(5, lower = 0, upper = 3) # "Must be <= 3, but is 5" ``` -------------------------------- ### Basic Coalesce Usage Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/framework.md Demonstrates the fundamental use of the %??% operator to provide a default value when the left operand is NULL. ```R NULL %??% 1 # 1 1 %??% 2 # 1 ``` -------------------------------- ### Check List Type Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Shows an error message when a list check fails due to a numeric input. ```r checkList(1:5) # "Must be of class 'list', but is 'numeric'" ``` -------------------------------- ### Handling NULL with null.ok = TRUE Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Demonstrates that `checkInteger` returns TRUE when the input is NULL and `null.ok` is set to TRUE, indicating successful validation under these conditions. ```r # NULL with null.ok = TRUE checkInteger(NULL, null.ok = TRUE) # TRUE ``` -------------------------------- ### Check Character Type Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Illustrates an error message when a character check fails due to a numeric input. ```r checkCharacter(1) # "Must be of type 'character', but is 'numeric'" ``` -------------------------------- ### Create Assertion Collection Source: https://github.com/mllg/checkmate/blob/master/_autodocs/configuration.md Initializes an assertion collection object. Use `$push()` to add messages, `$getMessages()` to retrieve them, and `$isEmpty()` to check if empty. ```r makeAssertCollection() ``` -------------------------------- ### Test DataFrame Minimum Row Count Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Shows an error when a data frame has fewer rows than the specified minimum. ```r testDataFrame(iris, min.rows = 200) # "Must have at least 200 rows, but has 150 rows" ``` -------------------------------- ### OR Logic for List or Character Vector with qtest Source: https://github.com/mllg/checkmate/blob/master/_autodocs/quick-assertion.md Demonstrates OR logic, accepting either an empty list or a character vector with at least one element. ```r # Accept either empty list OR character vector qtest(list(), c("l0", "s+")) # TRUE qtest(c("a", "b"), c("l0", "s+")) # TRUE qtest(1:3, c("l0", "s+")) # FALSE ``` -------------------------------- ### Test Duplicate Names Error Example Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Illustrates an error when a named vector contains duplicate names, violating the uniqueness requirement. ```r testNamed(c(a = 1, a = 2), type = "named") # "Must have unique names, but has duplicate names" ``` -------------------------------- ### wf and wl Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/utility-functions.md Efficient C implementations for finding the index of the first (wf) or last (wl) TRUE value in a logical vector. ```APIDOC ## wf / wl - Which First / Which Last ### Description Fast C implementations of `which.first()` and `which.last()`. `wf` returns the index of the first TRUE value, and `wl` returns the index of the last TRUE value in a logical vector. NA values are ignored. ### Signature ```r wf(x, use.names = TRUE) wl(x, use.names = TRUE) ``` ### Parameters - `x` (logical vector): The input logical vector. - `use.names` (logical): If TRUE, return results with names if `x` is named. Defaults to TRUE. ### Return Value Integer(1) representing the index of the first/last TRUE value, or integer(0) if no TRUE values are found. ### Behavior - `wf`: Index of first TRUE (or empty if all FALSE/NA). - `wl`: Index of last TRUE (or empty if all FALSE/NA). - NA values are ignored. - Equivalent to `head(which(x), 1)` and `tail(which(x), 1)` but faster. ### Examples ```r # First TRUE wf(c(FALSE, FALSE, TRUE, TRUE)) # 3 wf(c(FALSE, FALSE, FALSE)) # integer(0) # Last TRUE wl(c(FALSE, TRUE, FALSE, TRUE)) # 4 wl(c(FALSE, FALSE, FALSE)) # integer(0) # With names x <- c(a = FALSE, b = TRUE, c = FALSE, d = TRUE) wf(x, use.names = TRUE) # b (with name) wl(x, use.names = TRUE) # d (with name) # NA handling wf(c(FALSE, NA, TRUE)) # 3 (NA ignored) ``` ``` -------------------------------- ### Test Operating System Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/specialized-checks.md Checks the current operating system. Useful for conditional execution of OS-specific code. ```r # Check running on Linux if (testOS("linux")) { # Linux-specific code } # Assert Windows assertOS("windows") # Check any valid OS testOS() # Usually TRUE ``` -------------------------------- ### Inspect Collection of Assertions Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md This code demonstrates how to create an assertion collection, add multiple assertions to it, and then iterate through the collection to print any messages if assertions have failed. ```r coll <- makeAssertCollection() assertInteger(x, add = coll) assertNumeric(y, add = coll) if (!coll$isEmpty()) { for (msg in coll$getMessages()) { cat(" -", msg, "\n") } } ``` -------------------------------- ### Check Directory Existence and Accessibility Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/specialized-checks.md Validates that a directory exists and is accessible with specified permissions. Useful for ensuring output directories are ready. ```R testDirectoryExists("./data") # TRUE if exists ``` ```R testDirectoryExists("./output", access = "w") ``` ```R save_results <- function(output_dir) { assertDirectoryExists(output_dir, access = "w") # Continue... } ``` -------------------------------- ### Find first/last TRUE with named vectors Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/utility-functions.md Demonstrates using wf and wl with named logical vectors, returning the corresponding name if 'use.names' is TRUE. NA values are ignored in the search. ```r # With names x <- c(a = FALSE, b = TRUE, c = FALSE, d = TRUE) wf(x, use.names = TRUE) # b (with name) wl(x, use.names = TRUE) # d (with name) # NA handling wf(c(FALSE, NA, TRUE)) # 3 (NA ignored) ``` -------------------------------- ### Logical Scalar Checks with qtest Source: https://github.com/mllg/checkmate/blob/master/_autodocs/quick-assertion.md Demonstrates checking for a logical scalar, with and without NA allowance. ```r qtest(TRUE, "b1") # TRUE qtest(NA, "b1") # TRUE qtest(NA, "B1") # FALSE qtest(TRUE, "B1") # TRUE ``` -------------------------------- ### Recovery Strategy with Default Value Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Illustrates a recovery strategy where a function returns a default value instead of throwing an error if validation fails, using `testInteger`. ```r validate_or_default <- function(x, default) { if (testInteger(x, lower = 0)) { return(x) } return(default) } # Usage n_workers <- validate_or_default(args$workers, default = 1) ``` -------------------------------- ### Check File Existence and Readability Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/specialized-checks.md Validates that a file exists and is readable. Can also restrict checks to specific file extensions and verify write or execute permissions. ```R testFileExists("data.csv") # TRUE if file exists ``` ```R testFileExists("data.csv", extension = "csv") # TRUE ``` ```R testFileExists("data.txt", extension = "csv") # FALSE (wrong extension) ``` ```R testFileExists("output.txt", access = "w") # TRUE if writable ``` ```R process_file <- function(filepath) { assertFileExists(filepath, extension = c("txt", "csv")) # Continue... } ``` -------------------------------- ### checkDirectoryExists / assertDirectoryExists / testDirectoryExists / expect_directory_exists Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/specialized-checks.md Validates that a directory exists and is accessible with specified permissions. ```APIDOC ## checkDirectoryExists / assertDirectoryExists / testDirectoryExists / expect_directory_exists ### Description Validate that directory exists and is accessible. This function checks for directory existence and can validate read, write, or execute permissions. ### Signature ```r checkDirectoryExists(x, access = "r") assertDirectoryExists(x, access = "r", .var.name = vname(x), add = NULL) testDirectoryExists(x, access = "r") expect_directory_exists(x, access = "r", info = NULL, label = vname(x)) ``` ### Parameters #### Path Parameters - **x** (character(1)) - Required - Directory path - **access** (character(1)) - Optional - Access mode: "r", "w", "x". Defaults to "r". ### Return Value TRUE on success, error message/FALSE/expectation on failure. ### Behavior - Checks directory exists via dir.exists() - Validates access mode ### Examples ```r # Directory must exist testDirectoryExists("./data") # TRUE if exists # Writable directory for output testDirectoryExists("./output", access = "w") # In function save_results <- function(output_dir) { assertDirectoryExists(output_dir, access = "w") # Continue... } ``` ``` -------------------------------- ### Batch Validation Error Handling Strategy Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Shows how to use AssertCollection to perform batch validation, collecting all errors before reporting them at once using `reportAssertions`. ```r function(x, y, z) { coll <- makeAssertCollection() assertInteger(x, lower = 1, add = coll) assertNumeric(y, add = coll) assertFlag(z, add = coll) reportAssertions(coll) # Throws all at once (or not if empty) } ``` -------------------------------- ### checkOS / assertOS / testOS / expect_os Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/specialized-checks.md Validates the operating system. This is useful for writing platform-specific code or ensuring compatibility. ```APIDOC ## checkOS / assertOS / testOS / expect_os ### Description Validate the operating system. ### Signature ```r checkOS(os = NULL) assertOS(os = NULL, .var.name = vname(os), add = NULL) testOS(os = NULL) expect_os(os = NULL, info = NULL, label = vname(os)) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `os` | character | No | NULL | Expected OS name or NULL to check any | ### Behavior - If os = NULL, checks if running on known OS - If os specified, checks match ### Examples ```r # Check running on Linux if (testOS("linux")) { # Linux-specific code } # Assert Windows assertOS("windows") # Check any valid OS testOS() # Usually TRUE ``` ``` -------------------------------- ### Collection Errors Format Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Illustrates the format for reporting multiple assertion failures within a collection. It starts with the total count of failures and lists each individual error. ```r # Error message (N = 2): # 2 assertions failed: # * Variable 'x': Must be of type 'integer', but is 'double'. # * Variable 'y': Must be >= 0, but is -1. ``` -------------------------------- ### Integer Range and NA Check with qtest Source: https://github.com/mllg/checkmate/blob/master/_autodocs/quick-assertion.md Tests an integer vector for length greater than 0, no NAs, and values within [0, Inf). ```r qtest(1:3, "I+[0,)") # TRUE qtest(c(1, -1), "I+[0,)") # FALSE (has negative) qtest(c(1, NA), "I+[0,)") # FALSE (has NA) ``` -------------------------------- ### Validate Parameters with Collection Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/scalar-checks.md Use `makeAssertCollection` to group multiple assertions. `reportAssertions` then checks the collection. ```r validate_params <- function(n, prob, alpha) { coll <- makeAssertCollection() assertCount(n, add = coll) assertNumber(prob, lower = 0, upper = 1, add = coll) assertNumber(alpha, lower = 0, upper = 0.1, add = coll) reportAssertions(coll) } ``` -------------------------------- ### Three-Function Family Pattern Source: https://github.com/mllg/checkmate/blob/master/_autodocs/README.md Explains the common pattern of check*, assert*, test*, and expect_* functions. ```APIDOC ## Three-Function Family Pattern ### Description For many types, checkmate provides a family of functions: `check*`, `assert*`, `test*`, and `expect_*`. ### `check*` Functions - **Return:** `TRUE` on success, an error message string on failure. - **Use:** Low-level checks where you want to inspect the result. - **Example:** `result <- checkInteger(x)` ### `assert*` Functions - **Return:** Invisibly returns the input `x` on success. - **Effect:** Throws an error or collects an error in an `AssertCollection` on failure. - **Use:** Primarily for argument validation where immediate error reporting is desired. - **Example:** `assertInteger(x, .var.name = "count")` ### `test*` Functions - **Return:** `TRUE` on success, `FALSE` on failure. - **Use:** For conditional logic where exceptions are not desired. - **Example:** `if (testInteger(x)) { ... }` ### `expect_*` Functions - **Return:** A testthat/tinytest expectation object. - **Use:** For writing unit tests. - **Example:** `expect_integer(result)` ``` -------------------------------- ### Get Actual Check Result Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md This snippet shows how to capture the result of a check function into a variable and then inspect it. It's useful for debugging and understanding the exact error message returned. ```r # See exact error message msg <- checkInteger(x) if (!isTRUE(msg)) { print(msg) # See the error message } ``` -------------------------------- ### checkFileExists / assertFileExists / testFileExists / expect_file_exists Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/specialized-checks.md Validates that a file exists and is readable, with options to check writability, executability, and specific file extensions. ```APIDOC ## checkFileExists / assertFileExists / testFileExists / expect_file_exists ### Description Validate that file exists and is readable. This function checks for file existence and can also validate read, write, or execute permissions, and restrict checks to specific file extensions. ### Signature ```r checkFileExists(x, access = "r", extension = NULL) assertFileExists(x, access = "r", extension = NULL, .var.name = vname(x), add = NULL) testFileExists(x, access = "r", extension = NULL) expect_file_exists(x, access = "r", extension = NULL, info = NULL, label = vname(x)) ``` ### Parameters #### Path Parameters - **x** (character(1)) - Required - File path to check - **access** (character(1)) - Optional - Access mode: "r" (readable), "w" (writable), "x" (executable). Defaults to "r". - **extension** (character) - Optional - Allowed file extension(s) without dot, e.g. c("txt", "csv"). Defaults to NULL. ### Return Value TRUE on success, error message/FALSE/expectation on failure. ### Behavior - Checks file exists via file.exists() - Validates read/write/execute permissions if specified - Can restrict to specific extensions ### Examples ```r # File must exist and be readable testFileExists("data.csv") # TRUE if file exists # Restrict by extension testFileExists("data.csv", extension = "csv") # TRUE testFileExists("data.txt", extension = "csv") # FALSE (wrong extension) # Check writability testFileExists("output.txt", access = "w") # TRUE if writable # In function process_file <- function(filepath) { assertFileExists(filepath, extension = c("txt", "csv")) # Continue... } ``` ``` -------------------------------- ### OR Logic for Integer Sequence or NULL with qtest Source: https://github.com/mllg/checkmate/blob/master/_autodocs/quick-assertion.md Applies OR logic to accept an integer sequence with positive values or NULL. ```r # Accept integer sequence OR NULL qtest(1:10, c("I+[0,)")) # TRUE (passes first rule) ``` -------------------------------- ### Fail-Fast Error Handling Strategy Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Demonstrates the default fail-fast strategy where each assertion throws an error immediately upon failure, preventing subsequent checks. ```r function(x, y, z) { assertInteger(x, lower = 1) # Throws if invalid assertNumeric(y) # Never reached if x invalid assertFlag(z) # Never reached if x or y invalid } ``` -------------------------------- ### Matrix Dimension Check with qtest Source: https://github.com/mllg/checkmate/blob/master/_autodocs/quick-assertion.md Checks if the input is a matrix with at least 1 row and exactly 3 columns, and elements are integerish. ```r x = matrix(1:6, 2, 3) qtest(x, "m+x3") # checks rows ≥ 1, cols = 3 ``` -------------------------------- ### Parametric Tests with qtest Source: https://github.com/mllg/checkmate/blob/master/_autodocs/patterns.md Use `qtest` for concise validation in R tests, checking properties like type, length, and content of vectors. Provides a shorthand for common assertions. ```r test_that("quick assertions work", { expect_true(qtest(1:5, "i+")) # Integer vector, len > 0 expect_false(qtest(1.5, "I1")) # Not integer scalar expect_true(qtest(c(a=1, b=2), "n2")) # Numeric, len 2 }) ``` -------------------------------- ### OR Logic for List or Short Character Vector with qtest Source: https://github.com/mllg/checkmate/blob/master/_autodocs/quick-assertion.md Applies OR logic to check if input is either an empty list or a character vector with at most 5 elements. ```r qtest(list(), c("l0", "s<=5")) # TRUE qtest(letters[1:3], c("l0", "s<=5")) # TRUE qtest(letters[1:10], c("l0", "s<=5")) # FALSE ``` -------------------------------- ### Conditional Processing with Missing Value Detection Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/utility-functions.md Demonstrates using missing value detection (anyMissing) to handle optional processing, such as applying uniform weights if none are provided. ```r # Use missing value detection for optional processing process_data <- function(x, weights = NULL) { # Use uniform weights if not provided if (is.null(weights) || anyMissing(weights)) { weights <- rep(1, length(x)) } # Continue with weights } ``` -------------------------------- ### R6 Class Validation with Assertions Source: https://github.com/mllg/checkmate/blob/master/_autodocs/patterns.md Demonstrates how to use `assertNumeric` within an R6 class's `initialize` and `set_value` methods to enforce validation rules. The assertions ensure that the `value` parameter is a non-negative number. ```r MyClass <- R6::R6Class("MyClass", private = list(value_ = NULL), public = list( initialize = function(value) { assertNumeric(value, lower = 0) private$value_ <- value }, set_value = function(value) { assertNumeric(value, lower = 0) private$value_ <- value }, get_value = function() private$value_ ) ) # Usage obj <- MyClass$new(5) # OK obj$set_value(-1) # Error ``` -------------------------------- ### Conditional Warning for Infinite Values Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/utility-functions.md Demonstrates using `anyInfinite` to trigger a warning if infinite values are detected in a numeric vector. ```r # In validation if (anyInfinite(x)) { warning("x contains infinite values") } ``` -------------------------------- ### Utility Functions Source: https://github.com/mllg/checkmate/blob/master/_autodocs/README.md Helper functions for missing values, type testing, and function construction. ```APIDOC ## Utility Functions ### Description Helper functions for missing value detection, type testing, and constructing assertion/test/expectation functions. ### Functions - `anyMissing/allMissing`: Detect missing values. - `anyNaN/anyInfinite`: Detect special numeric values (NaN, Inf). - `isIntegerish`: Test if values are integerish. - `asInteger/asInt/asCount`: Convert and coerce to integer. - `wf/wl`: Efficiently find the first or last matching element. - `makeAssertion`: Create a custom assertion. - `makeAssertionFunction`: Generate assertion functions dynamically. - `makeTestFunction`: Generate test functions dynamically. - `makeExpectationFunction`: Generate expectation functions dynamically. - `register_test_backend`: Select the testing backend (testthat/tinytest). ``` -------------------------------- ### Conditional Logic with Missing Value Checks Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/utility-functions.md Demonstrates using `anyMissing` for conditional execution in R, ensuring data is complete before processing. ```r # Useful for conditional logic if (!anyMissing(x)) { # x is complete, safe to use result <- process(x) } ``` -------------------------------- ### Core Framework Functions Source: https://github.com/mllg/checkmate/blob/master/_autodocs/README.md Provides core functions for managing assertions, collections, and argument matching. ```APIDOC ## Core Framework Functions ### Description Core framework functions for combining checks, batching errors, reporting, and argument matching. ### Functions - `assert()`: Combine multiple checks. - `makeAssertCollection()`: Batch error collection. - `reportAssertions()`: Report collected errors. - `matchArg()`: Partial argument matching. - `vname()`: Extract variable name. - `%??%`: Coalesce operator. ``` -------------------------------- ### Assertion with qassert for Multiple Rules Source: https://github.com/mllg/checkmate/blob/master/_autodocs/quick-assertion.md Throws an error if the input `x` fails to meet either the 'integer of length 5' rule or the 'integer of length 4 with no NAs' rule. ```r # Multiple rules: error if ALL fail qassert(x, c("i5", "I4")) # Error if not (int len 5) AND not (int len 4, no NAs) ``` -------------------------------- ### OS-Specific Save Data Logic Source: https://github.com/mllg/checkmate/blob/master/_autodocs/api-reference/specialized-checks.md Saves data to a filepath, with conditional logic for Windows and Linux operating systems. ```r save_data <- function(filepath) { assertString(filepath) if (testOS("windows")) { # Windows-specific code } else if (testOS("linux")) { # Linux-specific code } } ``` -------------------------------- ### Inspecting Error Message Content Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Shows how to inspect the message of a caught error using `conditionMessage` and use `grepl` to check for specific error patterns, like bounds violations. ```r result <- tryCatch( assertNumeric(x, lower = 0), error = function(e) { msg <- conditionMessage(e) if (grepl("Must be >=", msg)) { # Handle bounds violation } return(NULL) } ) ``` -------------------------------- ### Handling NULL in List Source: https://github.com/mllg/checkmate/blob/master/_autodocs/errors.md Shows that `checkList` returns TRUE when a list contains NULL and `any.missing` is set to TRUE, validating lists where the presence of NULL is acceptable. ```r # NULL in list with any.missing = TRUE checkList(list(1, NULL), any.missing = TRUE) # TRUE ``` -------------------------------- ### Immediate Error Throwing Source: https://github.com/mllg/checkmate/blob/master/_autodocs/README.md Use assertion functions directly for fail-fast behavior. The function will immediately throw an error upon the first validation failure. ```r assertInteger(x) # Throws on failure ```