我在R中有一个名为tableOne的表,如下所示:
idNum        binaryVariable        salePrice
2               1                    55.56
4               0                    88.33
15              0                     4.45
87              1                    35.77
...            ...                    ...
我想从yield(tableOne $ salePrice)中获取的值通过salePrice创建四个四分位数.然后我想创建一个列tableOne $ quartile,每行sortPrice所在的四分位数.它看起来像:
idNum        binaryVariable            salePrice      quartile
    2               1                    55.56            3
    4               0                    88.33            4
    15              0                     4.45            1
    87              1                    35.77            2 
    ...            ...                    ...            ...  
有什么建议?
Tom*_*mmy 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等,以了解更多有关这里提到的功能...
数据表格方法
    library(data.table)
    tableOne <- setDT(tableOne)[, quartile := cut(salesPrice, quantile(salesPrice, probs=0:4/4), include.lowest=TRUE, labels=FALSE)]
小智 7
使用 dplyr,您可以使用 ntile 函数:
ntile(x, n)
tableOne$quartile <- ntile(tableOne$salesPrice, 4)
这将在表中添加一列,根据 n 为每一行分配一个分位数,其中包含价格分位数。
注意:此方法从 1 处的较低值开始,然后从那里向上工作。
设置参数labels=FALSEincut()以整数形式返回类别名称。看?cut
tableOne <- within(tableOne, quartile <- cut(salesPrice, quantile(salesPrice, probs=0:4/4), include.lowest=TRUE, labels=FALSE))
| 归档时间: | 
 | 
| 查看次数: | 29905 次 | 
| 最近记录: |