%macro corr(data=, y=, obs_freq=, exp_freq=, plot=, out=);
%let m=%sysfunc(countw(&y));

/*observed correlation*/
proc corr data=&data outp=obs_pcorr noprint;
	var &y;
	weight &obs_freq;
run;
data obs_pcorr;
	set obs_pcorr;
	if _type_ = 'CORR';
	drop _type_;
run;

/*observed correlation*/
proc corr data=&data outp=exp_pcorr noprint;
	var &y;
	weight &exp_freq;
run;
data exp_pcorr;
	set exp_pcorr;
	if _type_ = 'CORR';
	drop _type_;
run;

proc iml;
	use obs_pcorr;
	read all into obs;
	use exp_pcorr;
	read all into exp;

	k = 1; obs_corr = j(&m*(&m-1)/2, 1);exp_corr = j(&m*(&m-1)/2, 1);
	do i=2 to &m;
		do j=1 to i-1;
			obs_corr[k] = obs[i,j];
			exp_corr[k] = exp[i,j];
			k=k+1;
		end;
	end;

	create obs from obs_corr; append from obs_corr;
	create exp from exp_corr; append from exp_corr;
quit;

data temp;
	merge obs(rename=(col1=obs_corr)) exp(rename=(col1=exp_corr));
run;

data &out;
	set temp;
	retain profile 0;
	retain var1 1;
	retain var2 0;

	if var1-var2 = 1 then do;
		var1+1;
		var2=1;
	end;
	else var2+1;

	profile + 1;

	diff = obs_corr - exp_corr;
run;

proc datasets;
	delete obs_pcorr exp_pcorr obs exp temp;
run;quit;

proc sql noprint;
	select max(profile)
	into :max_profile
	from &out;
quit;

%if &plot='T' %then %do;
axis1 label=('X: The order in the lower triangle of the correlation matrix') order=(1 to &max_profile by 1);
axis2 label=('Correlation Residual') order=(-0.05 to 0.3 by 0.05);
title 'Correlation residual plot';
symbol i=j v=star;
proc gplot data=&out;
	plot diff*profile /haxis=axis1 vaxis=axis2 vref=0;
run;quit;
%end;
%mend;
