BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
Priyamvada07
Obsidian | Level 7

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??

1 ACCEPTED SOLUTION

Accepted Solutions
andreas_lds
Jade | Level 19

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;

View solution in original post

2 REPLIES 2
Kurt_Bremser
Super User

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;
andreas_lds
Jade | Level 19

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;

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 1416 views
  • 2 likes
  • 3 in conversation