Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use duplicate labels with cut function in R?

Tags:

r

If I have a vector of numbers, I know how to allocate them to categories using the cut function:

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

My issue is that I now want to project a range of numbers to color "lables" reusing colors, e.g. to get a stripe effect:

c<-cut(v,breaks=c(-10,0,3,8,Inf),labels=c("blue","green","blue","green"))

but this gives me an error:

factor level [3] is duplicated

I expected the cut function to project the categories to an index and then use that index to pick out the entry in the labels vector, but that doesn't seem to be the way it works. Is there a way to use repeated labels with "cut"?

like image 922
Adrian Tompkins Avatar asked Aug 16 '17 11:08

Adrian Tompkins


1 Answers

You can coerce to numeric, so it's no longer a factor, then use indices to match to your colors:

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" 
like image 117
Axeman Avatar answered Nov 09 '22 10:11

Axeman