Skip to content

Instantly share code, notes, and snippets.

@mbannert
Created December 4, 2014 15:21
Show Gist options
  • Select an option

  • Save mbannert/e9fcfa86de3b06068c83 to your computer and use it in GitHub Desktop.

Select an option

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

hadley commented Dec 4, 2014

Copy link
Copy Markdown

Or

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

@mbannert

mbannert commented Mar 9, 2015

Copy link
Copy Markdown
Author

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
Copy Markdown

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