concept stopifnot() in category R

appears as: stopifnot()
Exploring Data with R

This is an excerpt from Manning's book Exploring Data with R.

  • stopifnot() (Ensure the Truth of R Expressions)
  • The daily_sales() function is, without doubt, a great step up over the sales_on_day() function. But there is still more that could be done, and this involves checking inputs. Others that might use this function (or, even yourself!) may provide input values that simply won’t work inside the function body. Examples of erroneous inputs for the daily_sales() function might include character-based dates that are formatted differently (i.e., not in the ISO 8601 date format), a dataset that is different than what the function expects, or, perhaps a use of a TRUE or FALSE value for the dates argument. What we’ll do now is add some defensive programming statements to daily_sales(). These pieces of code will validate each of the inputs and stop the function at the first instance where the validation is not successful. There are two base R functions that are useful for stopping a function if: stop() and stopifnot(). Let’s use both of these on the next iteration of the daily_sales() function (Listing 7.28).

    Listing 7.47. How to stop the function if inputs are invalid.
    ```{r daily_sales_function_3}
    daily_sales <- function(sales_table,
                            dates = NULL) {
     
      if (!inherits(sales_table, "data.frame")) {                                     #A
        stop("The `sales_table` object should inherit from `data.frame`.")
      }
     
      summary_tbl <-
        sales_table %>%
        group_by(date) %>%
        summarize(
          order_count = n_distinct(order_id),
          items_sold = n(),
          total_revenue = sum(price)
        ) %>%
        arrange(desc(date))
     
      if (!is.null(dates)) {
       
        stopifnot(                                                                    #B
          is.character(dates) | inherits(dates, "Date"),                              #C
          grepl("[0-9]{4}-[0-9]{2}-[0-9]{2}", dates)                                  #D
        )
       
        dates <- as.Date(dates)
       
        summary_tbl <-
          summary_tbl %>%
          filter(date %in% dates)
      }
     
      summary_tbl
    }
    ```

    What’s changed from the previous version of this function (Listing 7.45) are the additions of a stop() statement within its own conditional if statement at the top of the function body, and, a stopifnot() statement inside the conditional if statement that is entered if dates are supplied by the user. Let’s examine each of these ways of stopping the function.