Skip to content

Instantly share code, notes, and snippets.

@JosepER
Last active May 25, 2020 14:57
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/0812f504211c8ff66d5cdeac201343a6 to your computer and use it in GitHub Desktop.
Save JosepER/0812f504211c8ff66d5cdeac201343a6 to your computer and use it in GitHub Desktop.
Compute the gini index with (optional) weights
#' Compute gini index.
#'
#' Compute the gini index with (optional) weights.
#'
#' @param x A numeric vector with the data.
#' @param weights A numeric vector with sample weights.
#' @return res An atomic vector with the gini index.
gini <- function(x, weights = NULL, na.rm = FALSE) {
if(na.rm){
index_nas <- is.na(x)
x <- x[!index_nas]
weights <- weights[!index_nas]
}
if(any(is.na(x))){
warning("There are NAs in 'x'. Use na.rm = TRUE to remove them.")
return(NA_real_)
}else if(!is.null(weight) & any(is.na(weight))){
warning("There are NAs in 'weights'. Use na.rm = TRUE to remove them.")
return(NA_real_)
}else{
ox <- order(x)
x <- x[ox]
weights <- weights[ox]/sum(weights)
p <- cumsum(weights)
nu <- cumsum(weights*x)
n <- length(nu)
nu <- nu/nu[n]
res <- sum(nu[-1]*p[-n])-sum(nu[-n]*p[-1])
return(res)
}
}
#' Compute gini index.
#'
#' Compute the gini index with (optional) weights.
#'
#' @param x A numeric vector with the data.
#' @param weights A numeric vector with sample weights.
#' @return res An atomic vector with the gini index.
gini <- function(x, weights = NULL, na.rm = FALSE) {
if(na.rm){
index_nas <- is.na(x)
x <- x[!index_nas]
weights <- weights[!index_nas]
}
if(any(is.na(x))){
warning("There are NAs in 'x'. Use na.rm = TRUE to remove them.")
return(NA_real_)
}else if(!is.null(weight) & any(is.na(weight))){
warning("There are NAs in 'weights'. Use na.rm = TRUE to remove them.")
return(NA_real_)
}else{
ox <- order(x)
x <- x[ox]
weights <- weights[ox]/sum(weights)
p <- cumsum(weights)
nu <- cumsum(weights*x)
n <- length(nu)
nu <- nu/nu[n]
res <- sum(nu[-1]*p[-n])-sum(nu[-n]*p[-1])
return(res)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment