Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 25 / 68

Creating your own condition

This lesson covers creating your own condition in R, with the aim of expressing kinds of error more specifically.

structure() lets you build a condition carrying your own class. Naming a class per kind of error makes it much easier to tell what went wrong.

In the sample code, check_age() builds a condition of class validationError with structure() when the age is below zero, and raises it with stop(). R's condition system plays much the same role as exception classes elsewhere.

A common early stumble is the distinctive syntax of that condition system. Compared with a plain stop("message"), building a custom class is fiddly and takes a while to feel natural.

In professional work, being able to tell "invalid input" apart from "the network failed" is what lets you write a suitable response to each.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)