alki
alki

Reputation: 3574

RGB to Hex converter

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"

Upvotes: 20

Views: 18489

Answers (4)

randy
randy

Reputation: 1081

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)

Upvotes: 2

SymbolixAU
SymbolixAU

Reputation: 26248

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"

Upvotes: 1

Hong Ooi
Hong Ooi

Reputation: 57686

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"

Upvotes: 41

joosts
joosts

Reputation: 164

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

Upvotes: -4

Related Questions