$title	Assign Households to Deciles

set	h	Households in the survey /h1*h2000/;

parameter	wt(h)	Sample weght associated with this household,
		n(h)	Number of individuals in the household,
		y(h)	Total household income
		ypc(h)	Per-capita household income,
		rank(h)	Household rank in per-capita,
		pct(h)	Percentile rankings for households;

*	This example is only illustrative:

wt(h) = uniform(0.5,1.5);
n(h) = uniform(1,5);
y(h) = uniform(0,1);

*	First we scale the household statistics to reflect sample weights:

n(h) = n(h) * wt(h);
y(h) = y(h) * wt(h);

*	Then compute per-capita income levels:

ypc(h) = y(h)/n(h);

*	Generate rankings for household based on the basis of
*	per-capita income:

$libinclude rank ypc h rank

alias (h,hh);
set	ranked(hh,h)	Sorted order;
loop(hh$(ord(hh)=1),
  ranked(hh+(rank(h)-1),h) = yes;
);

set	bug(h)	Check on hh bug;
bug(h) = yes$(sum(ranked(hh,h),1)<>1);
abort$card(bug) "Bug in ranking",bug;

parameter	ntot	Total population
		nsum	Household count
		nt(h)	Total number;

ntot = sum(h,n(h));
nsum = 0;
nt(h) = n(h);
loop(hh$(ord(hh) <= card(h)),
  loop(ranked(hh,h),
	nt(h) = nt(h) + nsum;
	nsum = nt(h);
  );
);

parameter	pct(h)	Percentile;
pct(h) = 100 * nt(h)/ntot;

set	dcl	Household decile assignments 
		/d10,d20,d30,d40,d50,d60,d70,d80,d90,d100/;

set	hdecile(h,dcl)  Assignment of households to deciles;

hdecile(h,dcl) = yes$((pct(h) > 100*(ord(dcl)-1)/10) 
		  and (pct(h) <= 100*ord(dcl)/10));
hdecile(h,dcl)$((pct(h)=0) and (ord(dcl)=1)) = yes;

parameter	fraction	Decile fractions;
fraction(dcl,"Persons")  = sum(hdecile(h,dcl), n(h));
fraction(dcl,"Weight")   = sum(hdecile(h,dcl), wt(h));
fraction(dcl,"NRecord")  = sum(hdecile(h,dcl), 1);
fraction(dcl,"IncomePC") = sum(hdecile(h,dcl), y(h)) /
			   sum(hdecile(h,dcl), n(h));
display fraction;



----    134 PARAMETER fraction  Decile fractions

         Persons      Weight     NRecord    IncomePC
d10      597.969     173.209     177.000       0.015
d20      595.655     174.285     176.000       0.040
d30      597.373     178.455     182.000       0.072
d40      601.488     167.700     168.000       0.101
d50      599.170     179.414     184.000       0.129
d60      597.411     170.169     174.000       0.157
d70      599.804     168.736     169.000       0.186
d80      596.160     181.639     182.000       0.220
d90      601.332     229.958     231.000       0.278
d100     598.606     354.177     357.000       0.460