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) } 83.186 126.931 138.6755 136.0540
#> { quantile(x, 0.5, na.rm = TRUE) } 289.410 300.901 357.3112 313.8055
#> { median(x, na.rm = TRUE) } 218.027 229.433 281.2705 236.8365
#> uq max neval
#> 153.8975 168.855 100
#> 435.1720 468.484 100
#> 362.4815 384.036 100