I have the following data
DATA HAVE;
input yr_2001 yr_2002 yr_2003 area;
cards;
1 1 1 3
0 1 0 4
0 0 1 3
1 0 1 6
0 0 1 4
;
run;
I want to do the following proc freq for variable yr_2001 to yr_2003.
proc freq data=have;
table yr_2001*area;
where yr_2001=1;
run;
Is there a way I can do it without having to repeat it for each year, may be using a loop for proc freq??
Start by transposing the data, so that do you don't have "data" in variable-names, then use by-statement in proc freq to create a table for each year.
data transposed;
set have;
length year $ 4 value 8;
array years yr_:;
do i = 1 to dim(years);
year = substr(vname(years[i]), 4);
value = years[i];
if value then output;
end;
drop yr_: i;
run;
proc sort data=transposed out=sorted;
by year;
run;
proc freq data=sorted;
by year;
table value*area;
run;
Your issue is bad data structure. See Maxim 19.
Transpose, then it's easy:
data have;
input yr_2001 yr_2002 yr_2003 area;
cards;
1 1 1 3
0 1 0 4
0 0 1 3
1 0 1 6
0 0 1 4
;
proc transpose
data=have
out=long (
where=(col1 = 1)
)
;
by area notsorted;
var yr:;
run;
proc freq data=long;
tables _name_*area;
run;
Start by transposing the data, so that do you don't have "data" in variable-names, then use by-statement in proc freq to create a table for each year.
data transposed;
set have;
length year $ 4 value 8;
array years yr_:;
do i = 1 to dim(years);
year = substr(vname(years[i]), 4);
value = years[i];
if value then output;
end;
drop yr_: i;
run;
proc sort data=transposed out=sorted;
by year;
run;
proc freq data=sorted;
by year;
table value*area;
run;
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
Still thinking about your presentation idea? The submission deadline has been extended to Friday, Nov. 14, at 11:59 p.m. ET.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.