Adrian Tompkins Adrian Tompkins - 6 months ago 77
R Question

How to use duplicate labels with cut function in 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"?

Answer Source

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" 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download