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;
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
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.