# These Codes are written by Reza Hajargasht for interpolation of Lorenz curves
# and associated functions using package "Schumaker".
#You need to install and call "Schumaker" and "GB2" libraries.
# Use of the codes is free as long as appropriate citations are made.
# Generating Data
# Data is generated from a GB2 distribition with parameters (a,b,p,q). I have here generated the data
# directly without any use of GB2 package but I am going to use the library later. Therefore I have called the library
library (GB2)
n=10000;ng=20; # n=number of toatal observations and ng=number of groups
;a=3.5; b=5;p=4;q=1
cc=seq(1/ng,1,1/ng)
z1=cc^(1/p);z1=z1[1:(ng-1)]
mu=(b*beta(p+1/a,q-1/a)/beta(p,q))*c(qbeta(z1,p+1/a,q-1/a),1);
yy=rbeta(n,p,q);
yy=(yy/(1-yy))^(1/a);yy=b*yy;
# Grouping the data
yy=sort(yy);
y=matrix(0,ng,1);z=matrix(0,ng,1);
c=n*cc;c=round(c);
for (i in 1:ng)
{
y[i]=sum(yy[1:(c[i])])/n
z[i]=yy[c[i]];
}
C=c(0,cc);L=c(0,y) # The data we actually have
C_int= seq(0,1,0.0001) # the points we do the interpolation for
library(schumaker)
# Lorenz, its First and Second Derivatives
SchumSpline = schumaker::Schumaker(C,L)
L_int = SchumSpline$Spline(C_int)
DL_int= SchumSpline$DerivativeSpline(C_int)
D2L_int = SchumSpline$SecondDerivativeSpline(C_int)
# Plot Lorenz
plot(C_int, L_int, type = "l", main = "Interpolated Lorenz Curve",ylab = "L_int", xlab = "C_int")
points(C,L)
# Plot CDF
plot(DL_int,C_int,col="red",main = "Interpolated CDF (red) vs True CDF (black)",ylab="",xlab="")
points(DL_int,pgb2(DL_int, a, b,p, q),"l",lwd=3)
# Plot Pdf
plot(DL_int, 1/(D2L_int),"l",col="red" ,main = "Interpolated PDF (red) vs True PDF (black)",ylab="",xlab="")
points(DL_int,dgb2(DL_int, a, b,p, q),cex=.5)