Skip to content

Instantly share code, notes, and snippets.

@JosepER
Created August 29, 2021 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosepER/0cf439dc2ae63c49ec13b19860c778fe to your computer and use it in GitHub Desktop.
Save JosepER/0cf439dc2ae63c49ec13b19860c778fe to your computer and use it in GitHub Desktop.
An R function wrapping over Julia's 'StatsBase.quantile()'
#' Weighted quantiles
#'
#' Wrap over Julia's 'StatsBase.quantile()' function.
#'
#' @param x A numeric vector for which the quantiles should be computed.
#' @param weights A numeric vector with the weights.
#' @param probs A numeric vector with the quantiles to compute.
#' @param na.rm a logical value indicating whether NA values should be stripped before the computation proceeds.
#'
#' @return A numeric vector with the weighted quantiles.
wtd_quantile <- function(x, weights = NULL, probs = c(0, 0.25, 0.5, 0.75, 1), na.rm = FALSE){
JuliaCall::julia_assign("weights_var", weights)
JuliaCall::julia_assign("v", x)
JuliaCall::julia_assign("probs", probs)
JuliaCall::julia_library("StatsBase")
JuliaCall::julia_command("wt = ProbabilityWeights(weights_var);")
if(na.rm){
JuliaCall::julia_eval("quantile(v[.!ismissing.(v)], wt[.!ismissing.(v)], probs)")
}else{
JuliaCall::julia_eval("quantile(v, wt, probs)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment