如何找到'平均'R中两列颜色的组合? [英] How can I find the 'average' of two columns of colors in R?
问题描述
我有一个颜色数据框,我想找到一种创建第三列的方法.第三列应包含其他两个列的混合色.我有一个示例数据框和一个我认为可以解决问题的函数.它使用R的 colorRampPalette()
函数和 purrr :: map2()
.但是,这将返回一个列出的列,该列在未列出时与数据框中的第一列相同.
I have a data frame of colors and I would like to find a way to create a third column. The third column should be comprised of a color that is a blend of the two other columns. I have an example data frame and a function that I thought would do the trick. It uses R's colorRampPalette()
function and purrr::map2()
. However, this returns a listed column that when unlisted is identical to the first column in the dataframe.
# Create a function for colors
x <- RColorBrewer::brewer.pal(11, 'Spectral')
spectral_col <- colorRampPalette(x)
# Apply this function to
tibble(first = sample(spectral_col(100)),
second = sample(spectral_col(100))) %>%
mutate(middle.color = map2(first, second, function(x, y){
k <- colorRampPalette(c(x, y))
k(1)
}))
有什么想法吗?
推荐答案
如果仅生成长度为 1
的调色板,则它将始终是第一个值.如:
If you just generate a palette of length 1
, it's always going to be the first value.
As in:
colorRampPalette(c("#000000","#FFFFFF"))(1)
#[1] "#000000"
您需要至少生成3个值才能采用两种指定颜色之间的中间值:
You need to generate at least 3 values to take the middle one between the two specified colours:
colorRampPalette(c("#000000","#FFFFFF"))(3)
#[1] "#000000" "#7F7F7F" "#FFFFFF"
colorRampPalette(c("#000000","#FFFFFF"))(3)[2]
#[1] "#7F7F7F"
如果要指定更精确的中点,也可以使用 colorRamp
作为替代:
You could also use colorRamp
as an alternative if you want to specify more precise mid-points:
rgb(colorRamp(c("#000000","#FFFFFF"))(0.5), max=255)
#[1] "#7F7F7F"
只要对r2evans感兴趣,就可以将其放在 purrr
函数中
With a hat-tip to r2evans, you can put this in your purrr
function:
dat <- tibble(first = sample(spectral_col(100)),
second = sample(spectral_col(100)))
dat %>%
mutate(middle=map2_chr(first,second, ~rgb(colorRamp(c(.x,.y))(0.5), max=255)))
或者在基R的 mapply
中:
mapply(function(x,y) rgb(colorRamp(c(x,y))(0.5), max=255), dat$first, dat$second)
这篇关于如何找到&#39;平均&#39;R中两列颜色的组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!