【问题标题】:Difference between ntile and cut and then quantile() function in RR中的ntile和cut然后分位数()函数之间的区别
【发布时间】:2017-05-29 22:39:34
【问题描述】:

我在这个主题上找到了两个线程来计算 R 中的十分位数。但是,这两种方法,即 dplyr::ntilequantile() 都会产生不同的输出。事实上,dplyr::ntile() 无法输出正确的十分位数。

方法一:使用 ntile()R: splitting dataset into quartiles/deciles. What is the right method? 线程,我们可以使用ntile()

这是我的代码:

vector<-c(0.0242034679584454, 0.0240411606258083, 0.00519255930109344, 
  0.00948031338483081, 0.000549450549450549, 0.085972850678733, 
  0.00231687756193192, NA, 0.1131625967838, 0.00539244534707915, 
  0.0604885614579294, 0.0352030947775629, 0.00935626135385923, 
  0.401201201201201, 0.0208212839791787, NA, 0.0462887301644538, 
  0.0224952741020794, NA, NA, 0.000984952654008562)

ntile(vector,10)

输出是:

ntile(vector,10)
5  5  2  3  1  7  1 NA  8  2  7  6  3  8  4 NA  6  4 NA NA  1

如果我们对此进行分析,我们会发现没有第 10 个分位数!

方法二:使用 quantile() 现在,让我们使用来自How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame 线程的方法。

这是我的代码:

as.numeric(cut(vector, breaks=quantile(vector, probs=seq(0,1, length  = 11), na.rm=TRUE),include.lowest=TRUE))

输出是:

 7  6  2  4  1  9  2 NA 10  3  9  7  4 10  5 NA  8  5 NA NA  1

正如我们所见,输出完全不同。我在这里想念什么?如有任何想法,我将不胜感激。

这是ntile() 函数中的错误吗?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    dplyr::ntileNA 总是排在最后(最高排名),这就是为什么在这种情况下您看不到第 10 个十分位的原因。如果您希望十分位数不考虑NAs,您可以定义一个类似here 的函数,我接下来使用它:

    ntile_na <- function(x,n)
    {
      notna <- !is.na(x)
      out <- rep(NA_real_,length(x))
      out[notna] <- ntile(x[notna],n)
      return(out)
    }
    
    ntile_na(vector, 10)
    # [1]  6  6  2  4  1  9  2 NA  9  3  8  7  3 10  5 NA  8  5 NA NA  1
    

    另外,quantile 有 9 种计算分位数的方法,您使用的是默认值,即数字 7(您可以查看 ?stats::quantile 以获得不同的 types,以及 here 以了解有关它们的讨论)。

    如果你尝试

    as.numeric(cut(vector, 
                   breaks = quantile(vector, 
                                     probs = seq(0, 1, length = 11), 
                                     na.rm = TRUE,
                                     type = 2),
                   include.lowest = TRUE))
    # [1]  6  6  2  4  1  9  2 NA  9  3  8  7  3 10  5 NA  8  5 NA NA  1
    

    您的结果与使用ntile 的结果相同。

    总而言之:这不是错误,只是它们的实现方式不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 2021-04-07
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      • 1970-01-01
      相关资源
      最近更新 更多