以相反的顺序枚举分位数

Enumerate quantiles in reverse order

我正在尝试获取数据框中列的分位数,但顺序相反。我希望最高数字在分位数 1 中。

这是我目前的情况:

> x<-c(10, 12, 75, 89, 25, 100, 67, 89, 4, 67, 120.2, 140.5, 170.5, 78.1)
> x <- data.frame(x)
> within(x, Q <- as.integer(cut(x, quantile(x, probs=0:5/5, na.rm=TRUE), 
  include.lowest=TRUE)))

       x Q
1   10.0 1
2   12.0 1
3   75.0 3
4   89.0 4
5   25.0 2
6  100.0 4
7   67.0 2
8   89.0 4
9    4.0 1
10  67.0 2
11 120.2 5
12 140.5 5
13 170.5 5
14  78.1 3

而我想要得到的是:

       x Q
1   10.0 5
2   12.0 5
3   75.0 3
4   89.0 2
5   25.0 4
6  100.0 2
7   67.0 4
8   89.0 2
9    4.0 5
10  67.0 4
11 120.2 1
12 140.5 1
13 170.5 1
14  78.1 3

一种方法是在 cut() 函数中指定反转标签。如果您希望 Q 是一个整数,那么您需要先将因子标签强制转换为一个字符,然后再转换为一个整数。

result <- within(x, Q <- as.integer(as.character((cut(x, 
                              quantile(x, probs = 0:5/5, na.rm = TRUE), 
                              labels = c(5, 4, 3, 2, 1),
                              include.lowest = TRUE)))))
head(result)
    x Q
1  10 5
2  12 5
3  75 3
4  89 2
5  25 4
6 100 2

您的数据:

x <- c(10, 12, 75, 89, 25, 100, 67, 89, 4, 67, 120.2, 140.5, 170.5, 78.1)
x <- data.frame(x)