Seydou GORO
Seydou GORO

Reputation: 1285

How to associate labels to code of colours

I have a certain number of labels and each label is associated with a code of colours.

#ABL==> "#828079FF"
#ANN===> "#D04D73FF"
#ANN2===> "#7A0403FF"
#BPD==> "#30B47CFF"
#BPG==> "#E2E418FF"
#BPG2==> "#F78112FF"
#SLE==> "#3480A4FF"
#SLE2==> "#3F4889FF"

I can have groups of labels that may differ from each other. Each time I have a vector of labels, I want another vector of corresponding colours to be created and in the same order.

For example if my label1 is:

[1] "BPD"  "BPG"  "SLE"  "SLE2"

my vector of colours to be created must be:

[1] "#30B47CFF" "#E2E418FF" "#3480A4FF" "#3F4889FF"

or if my label2 is:

[1]  "BPG"  "BPD"  "SLE2"

The vector of coulours to be created must be:

[1] "#E2E418FF" "#30B47CFF" "#3F4889FF"

Upvotes: 0

Views: 33

Answers (2)

jay.sf
jay.sf

Reputation: 73712

Assignment matrix (resp. data frame), then match(), convenient and clear.

A <- read.table(header=FALSE, text="
ABL  #828079FF
ANN  #D04D73FF
ANN2 #7A0403FF
BPD  #30B47CFF
BPG  #E2E418FF
BPG2 #F78112FF
SLE  #3480A4FF
SLE2 #3F4889FF
", comment.char='')

labs <-  c("BPD", "BPG", "SLE", "SLE2")

A[match(labs, A$V1), 2]
# [1] "#30B47CFF" "#E2E418FF" "#3480A4FF" "#3F4889FF"

Upvotes: 1

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 10010

Use named vectors in R:

label2color <- c("ABL" = "#828079FF",
"ANN" = "#D04D73FF",
"ANN2" = "#7A0403FF",
"BPD" = "#30B47CFF",
"BPG" = "#E2E418FF",
"BPG2" = "#F78112FF",
"SLE" = "#3480A4FF",
"SLE2" = "#3F4889FF")

label1 <- c("BPD",  "BPG",  "SLE",  "SLE2")
label2color[label1]

##         BPD         BPG         SLE        SLE2 
## "#30B47CFF" "#E2E418FF" "#3480A4FF" "#3F4889FF" 

Upvotes: 2

Related Questions