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"?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With