Skip to content

Instantly share code, notes, and snippets.

@statgeek
Created February 10, 2019 00:40
Show Gist options
  • Select an option

  • Save statgeek/ad1fa223bab22daf5a175faaa46491b1 to your computer and use it in GitHub Desktop.

Select an option

Save statgeek/ad1fa223bab22daf5a175faaa46491b1 to your computer and use it in GitHub Desktop.
SAS - Hypothesis Test for Variance
/*
Original Source: https://support.sas.com/kb/25/024.html
*/
%macro vartest(version,
data= _last_ ,
var= ,
alpha= 0.05 ,
var0=,
sigma0=
);
%if &version ne %then %put VARTEST macro Version 1.1;
%let opts = %sysfunc(getoption(notes))
_last_=%sysfunc(getoption(_last_));
%if &data=_last_ %then %let data=&syslast;
options nonotes;
%if &sigma0=0 or &var0=0 %then %do;
%put ERROR: The null hypothesis variance (VAR0=) or standard deviation;
%put %str( ) (SIGMA0=) must be greater than zero.;
%goto exit;
%end;
proc summary data=&data;
var &var;
output out=_varn(keep=var n std) n=n var=var std=std;
run;
data _vartest;
set _varn;
df=n-1;
%if &sigma0 ne %then %str(nullvar=&sigma0 * &sigma0;);
%if &var0 ne %then %str(nullvar=&var0;);
level=(1-&alpha)*100;
call symput('level',trim(left(level)));
%if &sigma0 ne or &var0 ne %then %do;
chisq=((df)*(var))/nullvar;
pvalue=1-probchi(chisq,df);
%end;
uclvar=df*var/cinv(&alpha/2,df); uclstd=sqrt(uclvar);
lclvar=df*var/cinv(1-&alpha/2,df); lclstd=sqrt(lclvar);
label var="Sample Variance" std="Sample Std Dev"
chisq="Chi-Square" pvalue="Prob>Chi-Square"
level="Confidence Level (%)"
uclvar="UCL for Variance" lclvar="LCL for Variance"
uclstd="UCL for Std Dev" lclstd="LCL for Std Dev";
drop df %if &sigma0 ne or &var0 ne %then nullvar; ;
run;
data _ci;
set _vartest;
stat="Variance"; estimate=var; lcl=lclvar; ucl=uclvar; output;
stat="Std Dev"; estimate=std; lcl=lclstd; ucl=uclstd; output;
label stat="Statistic"
estimate="Estimate"
lcl="Lower Confidence Limit"
ucl="Upper Confidence Limit";
run;
proc print data=_ci label noobs;
var stat estimate lcl ucl;
title "&level.% Confidence Intervals for Variance and Std Dev";
run;
%if &sigma0 ne or &var0 ne %then %do;
proc print data=_vartest label noobs;
var chisq pvalue;
format pvalue 6.4;
title "&level.% Hypothesis Test for";
title2;
%if &var0 ne %then %do;
title3 "H0: Variance(%upcase(&var)) = &var0";
title4 "Ha: Variance(%upcase(&var)) > &var0";
%end;
%if &sigma0 ne %then %do;
title3 "H0: StdDev(%upcase(&var)) = &sigma0";
title4 "Ha: StdDev(%upcase(&var)) > &sigma0";
%end;
run;
%end;
%exit:
title;
options &opts;
%mend;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment