我有以下data.frame
df<-data.frame(x=c("A","B","C"),colour=c(0.3,0.6,0.9))
x colour
1 A 0.3
2 B 0.6
3 C 0.9
我想用这样的颜色替换 df[,"color"] 中的数字
< 0.4 = colour 1
0.4 - 0.7 = colour 2
< 0.7= colour 3
我尝试了以下替换方案,但之前的颜色分配被后者替换了。有什么建议吗?
library(RColorBrewer)
g<-brewer.pal(3,"Greens")
col1<-df[,"colour"] < 0.4
df[col1,"colour"]<-g[1]
col2<-df[,"colour"] < 0.7
df[col2,"colour"]<-g[2]
col3<-df[,"colour"] >= 0.7
df[col3,"colour"]<-g[3]
谢谢你的建议。
解决方案感谢 seacarmody(和 spaceman 的有用评论)
v<-c(0.45,0.65,0.75,0.85,0.95)
breaks<-c(0.4,0.5,0.6,0.7,0.8,0.9)
#Create a colour for each section
cols<-brewer.pal(length(breaks)+1,"Greens")
#Replace the gsim values with colours using the breaks
v <- as.character(cut(v, c(-Inf, breaks, Inf),labels=cols))
> v
[1] "#C7E9C0" "#74C476" "#41AB5D" "#238B45" "#005A32"