20

Suppose I have this vector

x <- c("165 239 210", "111 45 93")

Is there a neat package to convert RGB values to hex values in R? I found many javascript ways but not one for R.

x <- "#A5EFD2" "#6F2D5D"
zx8754
  • 52,746
  • 12
  • 114
  • 209
alki
  • 3,334
  • 5
  • 22
  • 45

4 Answers4

37

Just split the string up, and then use rgb:

x <- c("165 239 210", "111 45 93")
sapply(strsplit(x, " "), function(x)
    rgb(x[1], x[2], x[3], maxColorValue=255))
#[1] "#A5EFD2" "#6F2D5D"
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
  • For me, I was going from `col2rgb` so the following shorthand works (and would be similar for the example here): `do.call(rgb, as.list(col2rgb('red')/255))` – MichaelChirico Apr 22 '19 at 07:39
  • Just FTR: after splitting the string, using a function makes this more versatile: `rgb_2_hex <- function(r,g,b){rgb(r, g, b, maxColorValue = 255)}` – aae Jul 09 '20 at 10:54
2

This answer is based off the answer to this same question by Hong Ooi but instead defines a function rgb2col function that takes as input a matrix of rgb values of the form returned by col2rgb. This means we can convert from hex to rgb and back again with just these two functions. In other words, rgb2col(col2rgb(x)) = col2rgb(rgb2col(x)) = x.

Input structure

Start with a matrix of RGB colors of the form returned by col2rgb(). For example:

      [,1] [,2]
red    213    0
green   94  158
blue     0  115

Function

This function will convert the matrix to a vector of hex colors.

rgb2col = function(rgbmat){
  # function to apply to each column of input rgbmat
  ProcessColumn = function(col){
    rgb(rgbmat[1, col], 
        rgbmat[2, col], 
        rgbmat[3, col], 
        maxColorValue = 255)
  }
  # Apply the function
  sapply(1:ncol(rgbmat), ProcessColumn)
}

Example use case

You might want to modify a color palette manually but not feel as comfortable working with hex numbers. For example, suppose I want to darken a vector of two colors a little.

# Colors to darken
ColorsHex = c("#D55E00","#009E73")

# Convert to rgb
# This is the step where we get the matrix
ColorsRGB = col2rgb(ColorsHex)

# Darken colors by lowering values of RGB
ColorsRGBDark = round(ColorsRGB*.7)

# Convert back to hex
ColorsHexDark = rgb2col(ColorsRGBDark)
randy
  • 1,031
  • 10
  • 20
1

You can convert to a numeric matrix and use colourvalues::convert_colours()

colourvalues::convert_colours( 
  matrix( as.numeric( unlist( strsplit(x, " ") ) ) , ncol = 3, byrow = T)
)
# [1] "#A5EFD2" "#6F2D5D"
SymbolixAU
  • 25,502
  • 4
  • 67
  • 139
-4

You could use the sprint function in R and the hints in the following post: How to display hexadecimal numbers in C?

Community
  • 1
  • 1
joosts
  • 154
  • 1
  • 6