checkmate icon indicating copy to clipboard operation
checkmate copied to clipboard

Add `prohibit_vector_recyling`

Open HughParsonage opened this issue 7 years ago • 1 comments

As a possible enhancement, consider a function like this:

prohibit_vector_recycling <- function(...){
  lengths <- vapply(list(...), FUN = length, FUN.VALUE = 0L)
  max.length <- max(lengths)
  if (any(lengths != 1L & lengths != max.length)){
    stop("Only permissible vector lengths are 1 or the maximum (nrow) of the inputs.")
  } else {
    invisible(max.length)
  }
}

The point of this function is to avoid nasty surprises from vector recycling and to a lesser extent to avoid checking multiple times. For example, if the inputs are being added to a data.frame

https://github.com/HughParsonage/grattan/blob/6db7207687b4df6c6b67087a9cf970fd4ddd44b3/R/income_tax.R#L159-L164

It seems a good fit for checkmate. I could have added this as a pull request, but I'm guessing you might prefer it to be implemented in C.

HughParsonage avatar Apr 16 '18 10:04 HughParsonage

I like the idea! I just need to come up with a name so that this fits into the existing naming scheme ...

assert_safely_recyclable() ?

I assume the number of vectors you usually pass is rather small, so C code is not necessarily required here. I would only replace the call to vapply() with lengths().

mllg avatar Apr 25 '18 07:04 mllg