Learn R Programming

erify

Check arguments and generate readable error messages.

Motivation

When creating functions for other people to use, you always need to

  1. check if the arguments passed by users are valid, and if not,
  2. generate informative and well-formatted error messages in a consistent style.

erify serves the exact purpose.

Installation

Install erify from CRAN:

install.packages("erify")

Or install the development version from Github:

# install devtools if not
# install.packages("devtools")

devtools::install_github("flujoo/erify")

Example

Suppose you are creating a function which prints a string several times to emphasize it:

# print `what` `n` times
emphasize <- function(what, n) {
  for (i in 1:n) {
    cat(what, "\n")
  }
}

# example
emphasize("You're beautiful!", 3)
#> You're beautiful! 
#> You're beautiful! 
#> You're beautiful!

And suppose a novice user accidentally passes a function to argument what, he/she will get an error message which is not very readable:

emphasize(c, 3)
#> Error in cat(what, "\n"): argument 1 (type 'builtin') cannot be handled by 'cat'

You can improve this by adding erify’s check_type() into emphasize():

emphasize <- function(what, n) {
  # check the type of `what`
  erify::check_type(what, "character")
  
  # main
  for (i in 1:n) {
    cat(what, "\n")
  }
}

emphasize(c, 3)
#> Error: `what` must have type character.
#> 
#> ✖ `what` has type builtin.

In the above code, check_type(what, "character") checks if what has type character, and if not, generates improved error message.

More

You can add more functions to check arguments, customize error messages, and create your own check functions.

See vignette("erify") for a gentle introduction to erify.

Copy Link

Version

Install

install.packages('erify')

Monthly Downloads

397

Version

0.6.0

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Renfei Mao

Last Published

June 30th, 2024

Functions in erify (0.6.0)

join

Connect Words with Conjunction
throw

Generate and Signal Condition
check_n

Check If Argument Is Single Natural Number
check_string

Check If Argument Is Single Character
check_length

Check Argument's Length
check_intervals

Check If Each Item Is in Interval
check_interval

Check If Argument Is in Interval
check_contents

Check Each Item's Content
check_bool

Check If Argument Is Single Logical
check_class

Check Argument's Class
back_quote

Back Quote Object
check_binary_classes

Check Binary Operator's Arguments' Classes
check_type

Check Argument's Type
check_positive

Check If Argument Is Single Positive Number
check_classes

Check Each Item's Class
check_content

Check Argument's Content
check_types

Check Each Item's Type
check_lengths

Check Each Item's Length