Search code examples
rcolorsalpha-transparency

How to get alpha value of a hexadecimal color in R


I would like to get alpha value of colors in a vector. However, I could not find any function for this.

However, I can parse the last part of the hexadecimal representation:

transparent.colors = alpha(c("red", "black"), alpha = 0.5)
transparency = substr(transparent.colors, start = 8, stop = 9)
strtoi(paste0("0x", transparency)) / 255

I think there should be some function implemented already. Any search often leads to irrelevant results (e.g. adding transparency to plots).


Solution

  • R doesn't have a built in alpha() function, so I'm going to assume you're using this alpha() function from the "scales" package.

    The best answer I could find was to use the built-in col2rgb() function. Try something like this:

    transparent.colors = alpha(c("red", "black"), alpha = 0.5)
    col2rgb(transparent.colors)[4] / 255
    col2rgb(transparent.colors, alpha=TRUE)["alpha",] # You can use the row name if you prefer.