rm(list = ls())
#calculate Gini coefficient
############################METHOD_1
library(ineq)
x <- c(541, 1463, 2445, 3438, 4437, 5401, 6392, 8304, 11904, 22261)
#type = c("Gini", "RS", "Atkinson", "Theil", "Kolm", "var","square.var", "entropy")
ineq(x,type = c("Gini"))
## [1] 0.4620911
x <- c(5,5,5,5)
ineq(x,type = c("Gini"))
## [1] 0
x <- c(1,1,1,1,1000)
ineq(x,type = c("Gini"))
## [1] 0.7960159
Gini(x, corr = FALSE, na.rm = TRUE)
## [1] 0.7960159
##########################METHOD_2
#install.packages("reldist")
library(reldist)
## reldist: Relative Distribution Methods
## Version 1.6-6 created on 2016-10-07.
## copyright (c) 2003, Mark S. Handcock, University of California-Los Angeles
##  For citation information, type citation("reldist").
##  Type help(package="reldist") to get started.
## 
## Attaching package: 'reldist'
## The following object is masked from 'package:ineq':
## 
##     entropy
x <- c(541, 1463, 2445, 3438, 4437, 5401, 6392, 8304, 11904, 22261)
gini(x,weights=rep(1,length=length(x)))
## [1] 0.4620911
## generate a vector of weights.
w <- seq(1,length(x),1)
gini(x,w)
## [1] 0.3775376
#########################METHOD_3
# Duoba and MacGibbon's function, reproduced as in the original paper:
StatsGini <- function(x, w = rep(1, length(x))){
  # x and w are vectors
  # w can be left blank when calling the fn (i.e. no weighting)
  # Examples:
  # x <- c(3, 1, 7, 2, 5)
  # w <- c(1, 2, 3, 4, 5)
  # StatsGini(x, w) should yield 0.2983050847
  # StatsGini(c(0.25, 0.75), c(1, 1)) should yield 0.25
  n <- length(x)
  wxsum <- sum(w * x)
  wsum <- sum(w)
  sxw <- order(x, w) # Ascending order sort
  sx <- w[sxw] * x[sxw]
  sw <- w[sxw]
  pxi <- vector(mode = "numeric", length = n)
  pci <- vector(mode = "numeric", length = n)
  pxi <- cumsum(sx) / wxsum
  pci <- cumsum(sw) / wsum
  G <- 0.0
  for (i in 2:n){
    G <- G - (pci[i] * pxi[i - 1] - pxi[i] * pci[i - 1] )
  }
  return(G)
}
StatsGini(x,w)
## [1] 0.3775376
####################REF
#http://freerangestats.info/blog/2017/08/05/weighted-gini