Last active
May 25, 2020 14:57
-
-
Save JosepER/0812f504211c8ff66d5cdeac201343a6 to your computer and use it in GitHub Desktop.
Compute the gini index with (optional) weights
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
#' 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) | |
} | |
} |
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
#' 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