Skip to content

Instantly share code, notes, and snippets.

@mbannert
Created December 4, 2014 15:21
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbannert/e9fcfa86de3b06068c83 to your computer and use it in GitHub Desktop.
Save mbannert/e9fcfa86de3b06068c83 to your computer and use it in GitHub Desktop.
Convert RGB to hex in R
rgb2hex <- function(r,g,b) sprintf('#%s',paste(as.hexmode(c(r,g,b)),collapse = ''))
rgb2hex(255,0,0)
# returns '#ff0000'
@hadley
Copy link

hadley commented Dec 4, 2014

Or

rgb2hex <- function(r,g,b) rgb(r, g, b, maxColorValue = 255)

@mbannert
Copy link
Author

mbannert commented Mar 9, 2015

Needed it again after months, looked it up, found my own tweet that led me to this git, just to learn @hadley beat on this :)

@davidorme
Copy link

And hence a derivative work: a function to turn a color name into hex, including alpha.

col2hex <- function(col, alpha) rgb(t(col2rgb(col)), alpha=alpha, maxColorValue=255)
col2hex('firebrick')
# [1] "#B22222"
col2hex('firebrick', 204)
# [1] "#B22222CC"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment