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 col2rgb()
to test if it is a color:
isColor <- function(x)
{
res <- try(col2rgb(x),silent=TRUE)
return(!"try-error"%in%class(res))
}
> isColor("white")
[1] TRUE
> isColor("#000000")
[1] TRUE
> isColor("foo")
[1] FALSE
Works, but doesn't seem very pretty and isn't vectorized. Second thing is to just check if the string is in the colors()
vector or a #
followed by a hexadecimal number of length 4 to 6:
isColor2 <- function(x)
{
return(x%in%colors() | grepl("^#(\\d|[a-f]){6,8}$",x,ignore.case=TRUE))
}
> isColor2("white")
[1] TRUE
> isColor2("#000000")
[1] TRUE
> isColor2("foo")
[1] FALSE
Which works though I am not sure how stable it is. But it seems that there should be a built in function to make this check?