r bin 相等的十分位数
r bin equal deciles
我有一个包含 6,000 多个观察值的数据集,每个记录的分数范围为 0-100。以下是示例:
+-----+-------+
| uID | score |
+-----+-------+
| 1 | 77 |
| 2 | 61 |
| 3 | 74 |
| 4 | 47 |
| 5 | 65 |
| 6 | 51 |
| 7 | 25 |
| 8 | 64 |
| 9 | 69 |
| 10 | 52 |
+-----+-------+
我想根据他们在分数列中相对于他们的同龄人的排名顺序将他们分成相等的十分位数,截止值是每 10 个百分位数,如下所示:
+-----+-------+-----------+----------+
| uID | score | position% | scoreBin |
+-----+-------+-----------+----------+
| 7 | 25 | 0.1 | 1 |
| 4 | 47 | 0.2 | 2 |
| 6 | 51 | 0.3 | 3 |
| 10 | 52 | 0.4 | 4 |
| 2 | 61 | 0.5 | 5 |
| 8 | 64 | 0.6 | 6 |
| 5 | 65 | 0.7 | 7 |
| 9 | 69 | 0.8 | 8 |
| 3 | 74 | 0.9 | 9 |
| 1 | 77 | 1 | 10 |
+-----+-------+-----------+----------+
到目前为止,我已经尝试过 cut、cut2、tapply 等。我认为我的逻辑路径是正确的,但我不知道如何将它们应用到我的情况中。非常感谢任何帮助。
我会在 dplyr
中使用 ntile()
。
library(dplyr)
score<-c(77,61,74,47,65,51,25,64,69,52)
ntile(score, 10)
##[1] 10 5 9 2 7 3 1 6 8 4
scoreBin<- ntile(score, 10)
在base R
中我们可以使用.bincode()
和quantile()
的组合:
df$new <- .bincode(df$score,
breaks = quantile(df$score, seq(0, 1, by = 0.1)),
include.lowest = TRUE)
# uID score new
#1 1 77 10
#2 2 61 5
#3 3 74 9
#4 4 47 2
#5 5 65 7
#6 6 51 3
#7 7 25 1
#8 8 64 6
#9 9 69 8
#10 10 52 4
这里是使用 quantile
和 cut
来获取 bins 的方法:
df$scoreBin <- as.integer(cut(df$score,
breaks=quantile(df$score, seq(0,1, .1), include.lowest=T)))
as.integer
将 cut 的输出(这是一个因子)强制转换为基础整数。
获取位置百分比的一种方法是使用 rank
:
df$position <- rank(df$score) / nrow(df)
我有一个包含 6,000 多个观察值的数据集,每个记录的分数范围为 0-100。以下是示例:
+-----+-------+
| uID | score |
+-----+-------+
| 1 | 77 |
| 2 | 61 |
| 3 | 74 |
| 4 | 47 |
| 5 | 65 |
| 6 | 51 |
| 7 | 25 |
| 8 | 64 |
| 9 | 69 |
| 10 | 52 |
+-----+-------+
我想根据他们在分数列中相对于他们的同龄人的排名顺序将他们分成相等的十分位数,截止值是每 10 个百分位数,如下所示:
+-----+-------+-----------+----------+
| uID | score | position% | scoreBin |
+-----+-------+-----------+----------+
| 7 | 25 | 0.1 | 1 |
| 4 | 47 | 0.2 | 2 |
| 6 | 51 | 0.3 | 3 |
| 10 | 52 | 0.4 | 4 |
| 2 | 61 | 0.5 | 5 |
| 8 | 64 | 0.6 | 6 |
| 5 | 65 | 0.7 | 7 |
| 9 | 69 | 0.8 | 8 |
| 3 | 74 | 0.9 | 9 |
| 1 | 77 | 1 | 10 |
+-----+-------+-----------+----------+
到目前为止,我已经尝试过 cut、cut2、tapply 等。我认为我的逻辑路径是正确的,但我不知道如何将它们应用到我的情况中。非常感谢任何帮助。
我会在 dplyr
中使用 ntile()
。
library(dplyr)
score<-c(77,61,74,47,65,51,25,64,69,52)
ntile(score, 10)
##[1] 10 5 9 2 7 3 1 6 8 4
scoreBin<- ntile(score, 10)
在base R
中我们可以使用.bincode()
和quantile()
的组合:
df$new <- .bincode(df$score,
breaks = quantile(df$score, seq(0, 1, by = 0.1)),
include.lowest = TRUE)
# uID score new
#1 1 77 10
#2 2 61 5
#3 3 74 9
#4 4 47 2
#5 5 65 7
#6 6 51 3
#7 7 25 1
#8 8 64 6
#9 9 69 8
#10 10 52 4
这里是使用 quantile
和 cut
来获取 bins 的方法:
df$scoreBin <- as.integer(cut(df$score,
breaks=quantile(df$score, seq(0,1, .1), include.lowest=T)))
as.integer
将 cut 的输出(这是一个因子)强制转换为基础整数。
获取位置百分比的一种方法是使用 rank
:
df$position <- rank(df$score) / nrow(df)