Created
August 29, 2021 16:13
-
-
Save JosepER/0cf439dc2ae63c49ec13b19860c778fe to your computer and use it in GitHub Desktop.
An R function wrapping over Julia's 'StatsBase.quantile()'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' 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