Thanks for the discussion. I've also wanted to be able to find nearest colors. I took the code and comments in this thread and simplified the function even further. (Personally, I think using closures results in Rube-Goldberg code. YMMV.) The first example below is what I use for 'group' colors in lattice.
Kevin Wright rgb2col <- function(cols.hex, near=.25){ # Given a vector of hex colors, find the nearest 'named' R colors # If no color closer than 'near' is found, return the hex color # Authors: John Fox, Martin Maechler, Kevin Wright # From r-help discussion 5.30.13 find.near <- function(x.hsv) { # return the nearest R color name and distance sq.dist <- colSums((all.hsv - x.hsv)^2) rbind(all.names[which.min(sq.dist)], min(sq.dist)) } all.names <- colors() all.hsv <- rgb2hsv(col2rgb(all.names)) cols.hsv <- rgb2hsv(col2rgb(cols.hex)) cols.near <- apply(cols.hsv, 2, find.near) ifelse(cols.near[2,] < near^2, cols.near[1,], cols.hex) } mycols <- c("royalblue", "red", "#009900", "dark orange", "#999999", "#a6761d", "#aa00da") mycols <- c("#010101", "#EEEEEE", "#AA0000", "#00AA00", "#0000AA", "#AAAA00", "#AA00AA", "#00AAAA") mycols <- c("#010101", "#090909", "#090000", "#000900", "#000009", "#090900", "#090009", "#000909") oldnew <- c(mycols, rgb2col(mycols, near=.25)) # Also try near=10 pie(rep(1,2*length(mycols)), labels=oldnew, col=oldnew) [[alternative HTML version deleted]] ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.