用 R 在矩阵中找到每一行的分位数的最快方法是什么?

What is the fastest way to find quantiles of each row in a matrix with R?

D <- matrix(rnorm(2000), nrow=2, ncol=1000)

t(matrix(c(quantile(D[1,], c(0.05,0.95)), quantile(D[2,], c(0.05,0.95))), nrow=2))

我有一个 2×1000 矩阵,其每一列都是 (X,Y) 的一对观测值。我想找到每一行的相同分位数。说 q_0.05 和 q_0.95。最快的计算方法是什么?

尝试matrixStats::rowQuantiles

library(matrixStats)
microbenchmark::microbenchmark(baseR=apply(D, 1, quantile, c(0.05, 0.95)),
                               matrixStats=rowQuantiles(D, probs=c(.05, .95)), 
                               times=10L)

# Unit: milliseconds
#        expr     min       lq     mean   median       uq      max neval cld
#       baseR 222.127 227.1580 238.7553 229.6283 233.1329 326.8730    10   b
# matrixStats 145.262 160.9838 171.9204 161.8530 168.4477 263.1476    10  a 

y1 <- t(apply(D, 1, quantile, c(.05, .95)))
y2 <- rowQuantiles(D, probs=c(.05, .95))
stopifnot(all.equal(y1, y2))

数据:

set.seed(42)
D <- matrix(rnorm(2e6), nrow=2, ncol=2e6)