Short question, if I have a string, how can I test if that string is a valid color representation in R
?
Two things I tried, first uses the function co
Your first idea (using col2rgb()
to test color names' validity for you) seems good to me, and just needs to be vectorized. As for whether it seems pretty or not ... lots/most R functions aren't particularly pretty "under the hood", which is a major reason to create a function in the first place! Hides all those ugly internals from the user.
Once you've defined areColors()
below, using it is easy as can be:
areColors <- function(x) {
sapply(x, function(X) {
tryCatch(is.matrix(col2rgb(X)),
error = function(e) FALSE)
})
}
areColors(c(NA, "black", "blackk", "1", "#00", "#000000"))
# black blackk 1 #00 #000000
# TRUE TRUE FALSE TRUE FALSE TRUE