Reputation: 1972
I am using the R function cut2
in the library Hmisc
. I am giving it a vector of numbers which it then turns into equally sized intervals:
library(Hmisc)
vals = c(100, 1000, 2000, 3000, 40000, 50000, 60000)
vals_cut = cut2(vals, g=3)
vals_cut
[1] [ 100, 3000) [ 100, 3000) [ 100, 3000) [ 3000,50000) [ 3000,50000) [50000,60000] [50000,60000]
Levels: [ 100, 3000) [ 3000,50000) [50000,60000]
The problem arises when I try to use vals_cut
on images when I share with others (e.g. on statistical graphics). People have found the output hard to read because a) the numbers do not have commas and b) there is not a space between the comma and the start of the second number.
I cannot find any options to cut2 which would modify the output in this way. Can anyone recommend an easy way to do this? Thanks.
Upvotes: 2
Views: 806
Reputation: 226212
Example:
library(Hmisc)
vals <- c(100, 1000, 2000, 3000, 40000, 50000, 60000)
vals_cut = cut2(vals, g=3)
vals_cut
This basically works; you might want to make cosmetic adjustments.
library(stringr)
trans_level <- function(x,nsep=" to ") {
n <- str_extract_all(x,"\\d+")[[1]] ## extract numbers
v <- format(as.numeric(n),big.mark=",",trim=TRUE) ## change format
x <- as.character(x)
paste0(
substring(x, 1, 1),
paste(v,collapse=nsep),
substring(x, nchar(x), nchar(x))) ## recombine
}
vals_cut2 <- vals_cut
levels(vals_cut2) <- sapply(levels(vals_cut),trans_level)
vals_cut2
[1] [100 to 3,000) [100 to 3,000) [100 to 3,000) [3,000 to 50,000) [3,000 to 50,000) [50,000 to 60,000] [50,000 to 60,000]
Levels: [100 to 3,000) [3,000 to 50,000) [50,000 to 60,000]
Upvotes: 3
Reputation: 1210
Here is a function just to format the levels of the intervals:
formatInterval <- function(x, intsep=", ") {
if (length(x) > 1) {
sapply(x, formatInterval, intsep=intsep)
} else {
makePretty <- function(z) {
prettyNum(gsub("[^0-9]", "", z), big.mark=",")
}
bracket1 <- substr(x, 1, 1)
bracket2 <- substr(x, nchar(x), nchar(x))
x2 <- strsplit(x, ",")
paste(bracket1,
makePretty(x2[[1]][1]),
intsep,
makePretty(x2[[1]][2]),
bracket2,
sep="")
}
}
Now
> levels(vals_cut) <- formatInterval(levels(vals_cut))
> vals_cut
[1] [100, 3,000) [100, 3,000) [100, 3,000) [3,000, 50,000) [3,000, 50,000) [50,000, 60,000]
[7] [50,000, 60,000]
Levels: [100, 3,000) [3,000, 50,000) [50,000, 60,000]
Or this might look nicer
> formatInterval(levels(vals_cut), intsep=" - ")
[ 100, 3000) [ 3000,50000) [50000,60000]
"[100 - 3,000)" "[3,000 - 50,000)" "[50,000 - 60,000]"
Upvotes: 2