Check if character string is a valid color representation

后端 未结 2 1008
终归单人心
终归单人心 2021-02-03 19:16

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

2条回答
  •  无人共我
    2021-02-03 20:04

    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 
    

提交回复
热议问题