Reputation: 615
I have this piece of code,
breaks=quantile(foo1$mnqtp, probs=seq(0,1, by=0.2))
Try 1
foo1$quantile <- with(foo1, cut(mnqtp, breaks=quantile(mnqtp, probs=seq(0,1, by=0.2)),
labels=c("0%","20%","40%","60%","80%"),
include.lowest=TRUE))
Try 2
foo1$quantile <- with(foo1, cut(mnqtp, breaks),labels=names(breaks),include.lowest=TRUE)
All I want is to rename the labels automatically to 90%, 100%, 20% etc based on the quantile. I can do it manually using Try 1, but I would like to have an automatic solution to this. Could you please help?
Upvotes: 3
Views: 4176
Reputation: 9344
In response to the comments on my first answer, here is a formatted example with labels for the ranges:
quantiles <- function(x, probs = seq(0, 1, by = 0.2)) {
cut(x, breaks = qu <- quantile(x, probs = probs),
labels = names(qu)[-1], include.lowest = TRUE)
}
makeRange <- function(x) {
d <- diff(range(x))
m <- min(x)
factor(tapply(x, quantiles(x),
function(x) paste(paste0(round((range(x)-m)/d, 2)*100, '%'), collapse = ' - ')))
}
head(makeRange(iris$Sepal.Width))
# 20% 40% 60% 80% 100%
# 0% - 29% 33% - 42% 46% - 46% 50% - 58% 62% - 100%
# Levels: 0% - 29% 33% - 42% 46% - 46% 50% - 58% 62% - 100%
Upvotes: 0
Reputation: 9344
Maybe something like this?
foo1$quantile <- with(foo1, cut(mnqtp, breaks=qu <- quantile(mnqtp, probs=seq(0,1, by=0.2)),
labels=names(qu)[-1],
include.lowest=TRUE))
iris$quantile <- with(iris, cut(Sepal.Width,
breaks = qu <- quantile(Sepal.Width, probs = seq(0,1, by=0.2)),
labels = names(qu)[-1], include.lowest=TRUE))
head(iris$quantile)
# [1] 100% 40% 80% 60% 100% 100%
# Levels: 20% 40% 60% 80% 100%
Upvotes: 2