Skip to content

Instantly share code, notes, and snippets.

@ateucher
Created January 6, 2015 21:37
Show Gist options
  • Save ateucher/91ecf757e5e042f9207f to your computer and use it in GitHub Desktop.
Save ateucher/91ecf757e5e042f9207f to your computer and use it in GitHub Desktop.
Convert R colours and rgb values to hex
col2hex <- function(colour) {
col_rgb <- t(col2rgb(colour))
rgb2hex(red = col_rgb[,1], green = col_rgb[,2], blue = col_rgb[,3])
}
rgb2hex <- function(red, green, blue, rgbvec = NULL) {
if ((missing(red) || missing(green) || missing(blue)) && is.null(rgbvec)) {
stop("You must supply red, green, and blue OR rgbvec")
}
if (!is.null(rgbvec)) {
if (length(rgbvec) != 3) stop("rgbvec must be of length 3")
red <- rgbvec[1]
green <- rgbvec[2]
blue <- rgbvec[3]
}
reds_hex <- tohex(red)
greens_hex <- tohex(green)
blues_hex <- tohex(blue)
hexes <- paste0("#", reds_hex, greens_hex, blues_hex)
hexes
}
tohex <- function(n) {
if (!inherits(n, c("numeric", "integer"))) stop(" value is not numeric or integer")
if (!(n <= 255 && n >= 0)) stop("value must be between 0 and 255 (inclusive)")
format(as.hexmode(n), width = 2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment