问题
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)
}))
Any ideas?
回答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"
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"
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"
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)))
Or in base R's mapply
:
mapply(function(x,y) rgb(colorRamp(c(x,y))(0.5), max=255), dat$first, dat$second)
来源:https://stackoverflow.com/questions/51886163/how-can-i-find-the-average-of-two-columns-of-colors-in-r