如果我有一个数字向量,我知道如何使用cut函数将它们分配给类别:
v<-c(3,2,9,3,4,10,-4) # example vector
c<-cut(v,breaks=c(-10,0,3,8,Inf),labels=c("blue","yellow","green","orange"))
c
[1] yellow yellow orange yellow green orange blue
Levels: blue yellow green orange
我的问题是,我现在想要投射一系列数字来着色&#34;标签&#34;重用颜色,例如获得条纹效果:
c<-cut(v,breaks=c(-10,0,3,8,Inf),labels=c("blue","green","blue","green"))
但这给了我一个错误:
factor level [3] is duplicated
我希望 cut 函数将类别投影到索引,然后使用该索引来选择标签向量中的条目,但这似乎不是它的方式作品。有没有办法使用&#34; cut&#34;?
重复使用标签答案 0 :(得分:6)
您可以强制使用数字,因此它不再是一个因素,然后使用索引来匹配您的颜色:
v <- c(3,2,9,3,4,10,-4)
C <- cut(v, breaks = c(-10,0,3,8,Inf))
C <- as.numeric(C)
c("blue","green","blue","green")[C]
[1] "green" "green" "green" "green" "blue" "green" "blue"