# [Rd] Color mapping for R : col2rgb()

Martin Maechler Martin Maechler <maechler@stat.math.ethz.ch>
Mon, 2 Apr 2001 15:18:59 +0200

```>>>>> "BDR" == Prof Brian Ripley <ripley@stats.ox.ac.uk> writes:

BDR> On Mon, 2 Apr 2001, Martin Maechler wrote:
>>
>> This has been an old topic, brought up last year by
>> Jens Oehlschlaegel and even before by Ben Bolker and maybe others.
>>
>> Over the weekend I've finally taken some time,
>> and have implemented one new function on the R level,
>> basically exposing the underlying C function str2col() [main/graphics.c]
>>
>> col2rgb() accepts a vector of all three kind of R colors :
>>
>> 1:n     =  indices into palette()
>> name    =  an element of colors()
>> #rrggbb =  character with the rgb hex code.
>>
>> Per color, it returns an integer(3) vector   c(red,green,blue)
>> with elements from 0:255.
>>
>> Currently {in my implementation},
>> when
>> r <- col2rgb(col)
>> r is a list() of the same length as col, and  r[[j]] = c(red_j, green_j, blue_j)
>> e.g.
>> > str(col2rgb(paste("gold", 1:4, sep="")))
>> List of 4
>> \$ : int [1:3] 255 215 0
>> \$ : int [1:3] 238 201 0
>> \$ : int [1:3] 205 173 0
>> \$ : int [1:3] 139 117 0
>> >
>>
>> This has been the easiest way of a vectorizing implementation.
>> Are the strong reasons why, e.g. a matrix should be returned instead ?
>> The matrix can `easily' be built by, e.g.
>>
>> matrix(c(col2rgb(...) , recursive = TRUE), nrow = 3))
>>
>> If it is felt that one always wanted this matrix (and dimnames, too),
>> it would maybe make sense to compute it in C.

BDR> What do you get if you ask for one colour (the most common case?)?
BDR> A one-element list seems silly.

agreed.  Also, a matrix *is* a simpler structure anyway.
I'd plan to rather go for an
3 x n
matrix (even though  [n x 3] prints more nicely)
with  dimnames = list(c("red,"green","blue"), NULL)
I'd still return a (1-row) matrix even for length(col) == 1,
for (R) API reasons, but at least that can be used as if it was a 3-vector
in almost all situations.

Martin
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-devel mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-devel-request@stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```