mllg / checkmate

Fast and versatile argument checks
https://mllg.github.io/checkmate/
Other
263 stars 30 forks source link

Check for values that can be interpreted as colors #216

Closed nutterb closed 2 years ago

nutterb commented 2 years ago

Would there be any interest in a function that checks if the inputs can be interpreted as colors?

This seems to work pretty well, based on https://stackoverflow.com/a/13290832/1017276

library(checkmate)
checkColor <- function(x){
  are_color <- vapply(x, 
                      function(col){
                        tryCatch(is.matrix(col2rgb(col)), 
                                 error = function(e) FALSE)
                      }, 
                      logical(1))

  if (all(are_color)){
    return(TRUE)
  } else {
    return(sprintf("Elements must be valid colors, but {%s} are not", 
                   paste0(x[!are_color], collapse = ", ")))
  }
}

assertColor <- makeAssertionFunction(checkColor, use.namespace = FALSE)
testColor <- makeTestFunction(checkColor)

checkColor(c("xly", "blue"))
#> [1] "Elements must be valid colors, but {xly} are not"
checkColor(c("#1284CD", "#DC13F355"))
#> [1] TRUE

assertColor(c("xly", "blue"))
#> Error in eval(expr, envir, enclos): Assertion on 'c("xly", "blue")' failed: Elements must be valid colors, but {xly} are not.
testColor(c("xly", "blue"))
#> [1] FALSE

testColor(rgb(.1, .2, .3))
#> [1] TRUE
testColor(c(NA, 1:30))
#> [1] TRUE
tdeenes commented 2 years ago

I think this is too specific to be included in checkmate. Just as you demonstrated, implementing it in pure R as a utility function is relatively easy. However, implementing and maintaining a high-performant version in C would be a non-trivial effort. If you wish you can create a package for this utility and even publish it to CRAN so that others can then use it, too.

nutterb commented 2 years ago

That's a fair and reasonable response. Thanks.