Slightly faster than quantile
with
na.rm=TRUE
. The internal implementation uses the 'C++' function
std::nth_element
, which is significantly faster than base R
implementation when the length of input x
is less than 1e7
.
Examples
# create input x with NAs
x <- rnorm(10000)
x[sample(10000, 10)] <- NA
# compute median
res <- fastquantile(x, 0.5)
res
#> [1] 0.01298609
# base method
res == quantile(x, 0.5, na.rm = TRUE)
#> 50%
#> TRUE
res == median(x, na.rm = TRUE)
#> [1] TRUE
# Comparison
microbenchmark::microbenchmark(
{
fastquantile(x, 0.5)
},{
quantile(x, 0.5, na.rm = TRUE)
},{
median(x, na.rm = TRUE)
}
)
#> Unit: microseconds
#> expr min lq mean median
#> { fastquantile(x, 0.5) } 64.911 117.940 127.4682 126.5610
#> { quantile(x, 0.5, na.rm = TRUE) } 279.070 291.393 329.6699 300.4855
#> { median(x, na.rm = TRUE) } 213.037 224.053 257.4503 229.3675
#> uq max neval
#> 137.8215 189.143 100
#> 320.7135 470.899 100
#> 244.9165 398.473 100