| 1 |
coarsen <- function(x,...) UseMethod("coarsen") |
| 2 |
|
| 3 |
coarsen.numeric <- function(x, |
| 4 |
n=5, |
| 5 |
pretty=TRUE, |
| 6 |
quantiles=!pretty, |
| 7 |
breaks=NULL, |
| 8 |
brackets=FALSE, |
| 9 |
sep=if(brackets)";"else if(quantiles) "-" else " - ", |
| 10 |
left="[", |
| 11 |
right="]", |
| 12 |
range=FALSE, |
| 13 |
labels=NULL, |
| 14 |
...){ |
| 15 |
if(quantiles && missing(pretty)) pretty <- FALSE |
| 16 |
if(pretty && quantiles) stop("Only one of 'pretty' or 'quantiles' may be TRUE.") |
| 17 |
if(!(pretty || quantiles)) stop("At least one of 'pretty' or 'quantiles' must be TRUE.") |
| 18 |
if(length(breaks)) { |
| 19 |
pretty <- FALSE |
| 20 |
quantiles <- FALSE |
| 21 |
} |
| 22 |
lo <- min(x) |
| 23 |
hi <- max(x) |
| 24 |
|
| 25 |
if(pretty || quantiles){ |
| 26 |
if(pretty){ |
| 27 |
breaks <- pretty(x,n=n,...) |
| 28 |
lwr <- breaks[-length(breaks)] |
| 29 |
upr <- breaks[-1] |
| 30 |
} |
| 31 |
else if(quantiles){ |
| 32 |
p <- seq(from=0,to=1,length=n+1) |
| 33 |
p <- p[!(p %in% c(0,1))] |
| 34 |
breaks <- quantile(x,probs=p,...) |
| 35 |
lab <- names(breaks) |
| 36 |
breaks <- c(lo,breaks,hi) |
| 37 |
lwr <- c("0%",lab) |
| 38 |
upr <- c(lab,"100%") |
| 39 |
} |
| 40 |
} else { |
| 41 |
if(range) |
| 42 |
breaks <- c(lo,breaks,hi) |
| 43 |
lwr <- breaks[-length(breaks)] |
| 44 |
upr <- breaks[-1] |
| 45 |
} |
| 46 |
if(missing(labels)){ |
| 47 |
if(brackets) |
| 48 |
labels <- paste0(left,paste(lwr,upr,sep=sep),right) |
| 49 |
else |
| 50 |
labels <- paste(lwr,upr,sep=sep) |
| 51 |
} |
| 52 |
f <- cut(x,breaks=breaks,include.lowest=TRUE) |
| 53 |
if(length(labels)!=nlevels(f)) |
| 54 |
stop("Number of labels does not match the number of levels.") |
| 55 |
f <- factor(f,levels=levels(f),labels=labels) |
| 56 |
f |
| 57 |
} |