Search code examples
rcolors

Obtaining a single color name from a HEX input in R


When using color.id from the plotrix package, is it possible to get ONLY a single colour returned not a vector of colours? see this example:

color.id("#A1A295")

this returns: "gray62" "grey62"

Is there a way (or another package) that simply returns a single colour name?

Thanks.


Solution

  • Here is vectorized function based on what Limey said.

    get_color_name <- function(color_hex) {
      out = vector(length = length(color_hex))
      
      for(i in seq_along(color_hex)) {
        out[i] <- color.id(color_hex[i])[1]
      }
      out
      
    }
    get_color_name(rainbow(5))
    >[1] "red"          "yellow2"      "springgreen2" "dodgerblue2"  "magenta2"   
    get_color_name("#A1A295")
    >[1] "gray62"