如何创建一个四分位排名列?

问题描述 投票:25回答:6

我有一个名为tableOne R中像这样的表:

idNum        binaryVariable        salePrice
2               1                    55.56
4               0                    88.33
15              0                     4.45
87              1                    35.77
...            ...                    ...

我想借此从生产值:摘要(tableOne $ salePrice)由salePrice创建四个四分位数。然后我想创建一个列tableOne $四分位数与四分位各行salePrice是它会是什么样子:

idNum        binaryVariable            salePrice      quartile
    2               1                    55.56            3
    4               0                    88.33            4
    15              0                     4.45            1
    87              1                    35.77            2 
    ...            ...                    ...            ...  

有什么建议么?

r
6个回答
49
投票

这应该这样做:

tableOne <- within(tableOne, quartile <- as.integer(cut(salesPrice, quantile(salesPrice, probs=0:4/4), include.lowest=TRUE)))

...一些细节:

within功能非常适合计算新列。你不必称之为tableOne$salesPrice等列

tableOne <- within(tableOne, quartile <- <<<some expression>>>)

quantile函数计算的位数(或你的情况,四分位数)。 0:4/4计算结果为c(0, 0.25, 0.50, 0.75, 1)

最后,cut功能将您的数据到这些四分。但是,你得到怪异名称的factor,所以as.integer它变成组1,2,3,4

尝试?within等,详细了解这里所提到的功能...


8
投票

一个data.table方法

    library(data.table)
    tableOne <- setDT(tableOne)[, quartile := cut(salesPrice, quantile(salesPrice, probs=0:4/4), include.lowest=TRUE, labels=FALSE)]

3
投票

labels=FALSE设置参数cut()返回的类别名称为整数。见?cut

tableOne <- within(tableOne, quartile <- cut(salesPrice, quantile(salesPrice, probs=0:4/4), include.lowest=TRUE, labels=FALSE))

3
投票

随着dplyr你可以使用NTILE函数:

ntile(x, n)


tableOne$quartile <- ntile(tableOne$salesPrice, 4)

这将一列添加到表分配基于N与价格位数是在各行的分位数。

注意:此方法在1与较低值开始,并从那里工作向上。


0
投票

使用包cutr我们可以这样做:

# devtools::install_github("moodymudskipper/cutr")
library(cutr)
df$quartile <- smart_cut(df$salePrice, 4, "g", output = "numeric")
#   idNum binaryVariable salePrice quartile
# 1     2              1     55.56        3
# 2     4              0     88.33        4
# 3    15              0      4.45        1
# 4    87              1     35.77        2

-1
投票

您可以使用下面的脚本

tableOne$Quartile<-ifelse(tableOne$salesPrice<=quantile(tableOne$salesPrice,c(0.25)),1,
                           ifelse(tableOne$salesPrice<=quantile(tableOne$salesPrice,c(0.5)),2,
                                  ifelse(tableOne$salesPrice<=quantile(tableOne$salesPrice,c(0.75)),3,
                                         ifelse(tableOne$salesPrice<=quantile(tableOne$salesPrice,c(1)),4,NA))))
© www.soinside.com 2019 - 2024. All rights reserved.