假设我有这个向量
x <- c("165 239 210", "111 45 93")
在R中是否有一个方便的包可以将RGB值转换为十六进制值?我发现很多JavaScript的方法,但没有一个是针对R的。
x <- "#A5EFD2" "#6F2D5D"
只需将字符串拆分,然后使用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"
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"
col2rgb
开始的,所以下面的简写方式可以使用(并且在这个例子中也类似):do.call(rgb, as.list(col2rgb('red')/255))
- MichaelChiricorgb_2_hex <- function(r,g,b){rgb(r, g, b, maxColorValue = 255)}
- aae