我有以下列表
t <- c(22, 22, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 4, 4, 4, 18,
18, 18, 12, 12, 12, 1, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 6,
6, 6, 6, 6, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
21, 20, 20, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 2, 2, 2, 3, 3, 3, 3,
5, 5, 5, 5, 5, 10, 10, 10, 17, 17, 17, 14, 14, 15, 15, 15)
我想用这段代码为每种颜色分配颜色
library(RColorBrewer)
rowcol <- colorRampPalette(brewer.pal(8,"Dark2"))
rowcol(length(unique(t)))[t]
但是为什么会产生NAs?
[1] NA NA "#A66F20" "#A66F20" "#A66F20" "#A66F20" "#A66F20" "#A66F20" "#A66F20" "#A66F20" "#A66F20"
[12] "#578A52" "#578A52" "#578A52" "#578A52" "#578A52" "#578A52" "#578A52" "#8A6C8D" "#8A6C8D" "#8A6C8D" "#C9611D"
[23] "#C9611D" "#C9611D" "#1B9E77" "#93762D" "#93762D" "#93762D" "#93762D" "#93762D" "#93762D" "#93762D" "#93762D"
[34] "#93762D" "#93762D" "#93762D" "#93762D" "#93762D" "#93762D" "#93762D" "#93762D" "#93762D" "#7F6EA0" "#7F6EA0"
[45] "#7F6EA0" "#7F6EA0" "#7F6EA0" "#7F6EA0" "#7F6EA0" "#7F6EA0" "#7F6EA0" "#7F6EA0" "#7F6EA0" "#7F6EA0" "#7F7C39"
[56] "#7F7C39" "#7F7C39" "#7F7C39" "#7F7C39" NA NA NA NA NA NA NA
[67] NA NA NA NA NA NA NA "#7570B3" "#7570B3" "#BB6814" "#BB6814"
[78] "#BB6814" "#BB6814" "#BB6814" "#BB6814" "#BB6814" "#BB6814" "#BB6814" "#BB6814" "#D35F0B" "#D35F0B" "#D35F0B"
[89] "#D35F0B" "#D35F0B" "#D35F0B" "#D35F0B" "#D35F0B" "#D35F0B" "#D35F0B" "#D35F0B" "#D35F0B" "#D35F0B" "#D35F0B"
[100] "#D35F0B" "#2F976A" "#2F976A" "#2F976A" "#43905E" "#43905E" "#43905E" "#43905E" "#6B8345" "#6B8345" "#6B8345"
[111] "#6B8345" "#6B8345" "#CE6208" "#CE6208" "#CE6208" "#946A7B" "#946A7B" "#946A7B" "#B46543" "#B46543" "#A96755"
[122] "#A96755" "#A96755"
在一天结束时,我想在RowSideColors
中将此最终向量用作heatmap.2
参数。
答案 0 :(得分:4)
让我们使用你的矢量&#34; t&#34;:
unique(t)
的长度是多少?
length(unique(t))
# 20
如果我们使用rowcol
会发生什么:
pal <- rowcol(length(unique(t)))
pal
# [1] "#1B9E77" "#61864B" "#A66F20" "#CE6014" "#A96755" "#846D97" "#8D61AA" "#B7469B" "#E12C8C" "#BE5067" "#8E7E40"
# [12] "#6CA61C" "#9BA812" "#CBA907" "#DBA206" "#C48F10" "#AC7B1A" "#957130" "#7D6B4B" "#666666"
length(pal)
# 20
&#34; t&#34;的最大值是什么,即
max(t)
# 22
我们清楚地看到pal
的长度和&#34; t&#34;的最大值不匹配。这就是为什么当&#34; t&#34;如果等于21或22,则得NA
。
您需要使用rowcol(max(t))[t]
答案 1 :(得分:1)
因为:
length(unique(t))
#> [1] 20
max(t)
#> [1] 22
all(is.na(rowcol(length(unique(t)))[t]) == (t>20))
#> [1] TRUE
并且索引超出其索引的向量长度并不是错误;当索引(t
)超过其索引(rowcol(length(unique(t)))
)