2

I want to create intervals (discretize/bin) of continuous variables to plot a choropleth map using ggplot. After reading various threads, I decided to use cut and quantile to eliminate the problems of: a) manually creating bins, and b) taking care of dominant states (otherwise, I had to manually to create bins and see the map and readjust the bins).

However, I am facing another problem now. Intervals coming out of cut are hardly pretty. So, I am trying to follow this example and this example to come up with my pretty labels.

Here is my list:

x <- seq(1,50)

Rounded quantiles:

qs_x <- round(quantile(x, probs=c(seq(0,0.8,by=0.2),0.9)))

which results:

 0% 20% 40% 60% 80% 90% 
 1  11  21  30  40  45 

Using these cuts, I want to come up with these labels:

1-11, 12-21, 22-30, 31-40, 41-45, 45+

I am sure there is an easy solution to convert a list using some apply function, but I am not well-versed with those functions.

Help appreciated.

1 Answer 1

2

A 3-liner produces the output you want, without using apply.

labels <- paste(qs_x+1, qs_x[-1], sep="-")
labels[1] <- paste(qs_x[1], qs_x[2], sep="-")
labels[length(labels)] <- paste(tail(qs_x, 1), "+", sep = "")

The first line constructs labels of the form (x1 + 1) - x2, the second line fixes the first label, and the third line fixes the last label. Here is the output

> labels
[1] "1-11"  "12-21" "22-30" "31-40" "41-45" "45+"  
2
  • There is an extra label (41-45) in the output I provided, I assume that's what you need.
    – Ryogi
    Jul 11, 2012 at 18:32
  • thank you very much (yes, I do need that label that I missed from my example). I did something similar using a for loop. I think your code is better. Before I accept your answer, I will wait for some more time to see whether someone has even cleverer solution.
    – karlos
    Jul 11, 2012 at 19:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.