【问题标题】:how to calculate medians for unsorted dataset如何计算未排序数据集的中位数
【发布时间】:2014-08-30 06:00:54
【问题描述】:

我有成千上万个这样的数据集:

>student1
    quantities score
[1]          4    10         
[2]          1    12         
[3]         78     5         
[4]          6   294

我想计算这个学生的分数中位数。对于每个分数,我们都有一些数量。在这种情况下,我希望它返回 5,因为中位数是 78 个 5 之一。

我在这里查看了一些帖子,例如 how to calculate the median on grouped dataset? ,但我无法使用它,因为我有数千个数据集。

我也尝试安装aroma.light 包和matrixstats 包,但我仍然不能使用“weighted.median 函数”的东西。它告诉我

Error: could not find function "weightedMedians"

好的,上面只是一个例子,我的真实数据集是这样的:

>test
     [,1]          [,2]
info    3            10
info    2            20
        4      86779637
        1        135777
        7          2342

但是当我尝试使用时

>rep(test[, 1], test[, 2])

它出现了

Error in rep(test[, 1], test[, 2]) : invalid 'times' argument
In addition: Warning message:
NAs introduced by coercion 

我现在能做什么?

【问题讨论】:

    标签: r median


    【解决方案1】:

    你可以使用:

    median(rep(student1$score, student1$quantities))
    

    这相对较快(使用 10 万行的模拟数据集只需几秒钟)

    【讨论】:

    • 它告诉我invalid 'times' argument ?
    • 嗯,数量列可能有问题。没有看到实际数据就无法判断...
    【解决方案2】:

    matrixStats包中计算加权中位数的函数称为weightedMedian()(不带复数's'),例如

    > library("matrixStats")
    matrixStats v0.14.0 (2015-02-13) successfully loaded. See ?matrixStats for help.
    > weightedMedian(student1$score, w=student1$quantities)
    [1] 5.670732
    > weightedMedian(student1$score, w=student1$quantities, interpolate=FALSE)
    [1] 5
    

    【讨论】:

      猜你喜欢
      • 2013-09-24
      • 2020-09-01
      • 1970-01-01
      • 2017-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      相关资源
      最近更新 更多