【发布时间】:2015-10-12 23:57:36
【问题描述】:
假设我有这个向量
x <- c("165 239 210", "111 45 93")
是否有一个简洁的包将 RGB 值转换为 R 中的十六进制值?我发现了许多 javascript 方法,但没有一种用于 R。
x <- "#A5EFD2" "#6F2D5D"
【问题讨论】:
标签: r
假设我有这个向量
x <- c("165 239 210", "111 45 93")
是否有一个简洁的包将 RGB 值转换为 R 中的十六进制值?我发现了许多 javascript 方法,但没有一种用于 R。
x <- "#A5EFD2" "#6F2D5D"
【问题讨论】:
标签: r
只需将字符串拆分,然后使用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"
【讨论】:
col2rgb 出发的,所以以下速记有效(此处的示例与此类似):do.call(rgb, as.list(col2rgb('red')/255))
rgb_2_hex <- function(r,g,b){rgb(r, g, b, maxColorValue = 255)}
这个答案基于answer to this same question by Hong Ooi,而是定义了一个函数rgb2col函数,该函数将col2rgb返回的形式的rgb值矩阵作为输入。这意味着我们可以仅使用这两个函数将十六进制转换为 rgb 并再次转换回来。
换句话说,rgb2col(col2rgb(x)) = col2rgb(rgb2col(x)) = x。
从col2rgb() 返回的表单的RGB 颜色矩阵开始。例如:
[,1] [,2]
red 213 0
green 94 158
blue 0 115
此函数会将矩阵转换为十六进制颜色的向量。
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)
}
您可能想手动修改调色板,但对使用十六进制数字感到不舒服。例如,假设我想将两种颜色的向量变暗一点。
# 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)
【讨论】:
您可以转换为数字矩阵并使用colourvalues::convert_colours()
colourvalues::convert_colours(
matrix( as.numeric( unlist( strsplit(x, " ") ) ) , ncol = 3, byrow = T)
)
# [1] "#A5EFD2" "#6F2D5D"
【讨论】:
您可以使用 R 中的 sprint 函数和以下帖子中的提示:How to display hexadecimal numbers in C?
【讨论】: