neversaint
neversaint

Reputation: 63984

Using lapply with colorRampPalette

I have the following vector:

x <- c(1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 5, 5, 5, 5, 5, 5)

What I want to do is to assign color for each number using colorRampPalette. But why this command gives more output than I expected:

library(RColorBrewer)
mycolorfunction <- colorRampPalette(brewer.pal(9,"Set1"))
unlist(lapply(as.list(x),mycolorfunction))

It gives this:

 [1] "#E41A1C" "#E41A1C" "#E41A1C" "#E41A1C" "#999999" "#E41A1C" "#999999" "#E41A1C" "#999999" "#E41A1C" "#999999"
[12] "#E41A1C" "#999999" "#E41A1C" "#999999" "#E41A1C" "#999999" "#E41A1C" "#FF7F00" "#999999" "#E41A1C" "#FF7F00"
[23] "#999999" "#E41A1C" "#FF7F00" "#999999" "#E41A1C" "#7E6E85" "#E1C62F" "#999999" "#E41A1C" "#4DAF4A" "#FF7F00"
[34] "#A65628" "#999999" "#E41A1C" "#4DAF4A" "#FF7F00" "#A65628" "#999999" "#E41A1C" "#4DAF4A" "#FF7F00" "#A65628"
[45] "#999999" "#E41A1C" "#4DAF4A" "#FF7F00" "#A65628" "#999999" "#E41A1C" "#4DAF4A" "#FF7F00" "#A65628" "#999999"
[56] "#E41A1C" "#4DAF4A" "#FF7F00" "#A65628" "#999999"

I expect it to produce vector of size 20 with only 5 color Hex. What's the right way to do it?

At the end of the day I'd like to use the final vector as RowSideColors argument in heatmap.2.

Upvotes: 2

Views: 61

Answers (1)

user3710546
user3710546

Reputation:

Directly use you function mycolorfunction and x as a vector of indices:

x <- c(1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 5, 5, 5, 5, 5, 5)
library(RColorBrewer)
mycolorfunction <- colorRampPalette(brewer.pal(9,"Set1"))

mycolorfunction(max(x))[x]
#  [1] "#E41A1C" "#E41A1C" "#E41A1C" "#4DAF4A" "#4DAF4A" "#4DAF4A" 
#  [7] "#4DAF4A" "#4DAF4A" "#4DAF4A" "#4DAF4A" "#FF7F00" "#FF7F00"
# [13] "#FF7F00" "#A65628" "#999999" "#999999" "#999999" "#999999"
# [19] "#999999" "#999999"

Upvotes: 2

Related Questions