如何在cut函数中获取分位数标签名称?

时间:2014-08-01 18:27:05

标签: r

我有这段代码,

breaks=quantile(foo1$mnqtp, probs=seq(0,1, by=0.2))

尝试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))

尝试2

foo1$quantile <- with(foo1, cut(mnqtp, breaks),labels=names(breaks),include.lowest=TRUE)

我想要的是根据分位数自动将标签重命名为90%,100%,20%等。我可以使用Try 1手动完成,但我希望有一个自动解决方案。你能帮忙吗?

2 个答案:

答案 0 :(得分:1)

也许是这样的?

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%

答案 1 :(得分:0)

在回答我对第一个答案的评论时,这是一个带有范围标签的格式化示例:

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%
相关问题