BookmarkSubscribeRSS Feed
marleeakerson
Calcite | Level 5

Hello, 

 

I am trying to group by age and use the sums of the groups. For instance, if I am using this data table: 

 

Age Users
17 1
18 2
19 5
20 3
21 9
22 9
23 2
24 5
25 3
26 2

 

I want to make a new table that groups the age groups by three years and uses the sum of the 'users' variable for that age group. So the output table would look like: 

 

Age_group      Users

17-20                8

21-23                20

24-26                10

 

Does anyone know how to help write the code for this? 

2 REPLIES 2
Reeza
Super User

How did you get 8 for 17-20? 1+ 2 + 5+ 3 = 11?

Otherwise it just looks like a formatted output.

proc format;
value age_fmt
17 - 20 = '17 - 20'
21 - 23 = '21 - 23'
24-26 = '24 - 26';
run;

proc freq data=have;
table age ;
weight users;
format age age_fmt.;
run;

Fully worked example is available here:

https://github.com/statgeek/SAS-Tutorials/blob/master/proc_format_example.sas

 


@marleeakerson wrote:

Hello, 

 

I am trying to group by age and use the sums of the groups. For instance, if I am using this data table: 

 

Age Users
17 1
18 2
19 5
20 3
21 9
22 9
23 2
24 5
25 3
26 2

 

I want to make a new table that groups the age groups by three years and uses the sum of the 'users' variable for that age group. So the output table would look like: 

 

Age_group      Users

17-20                8

21-23                20

24-26                10

 

Does anyone know how to help write the code for this? 


 

ballardw
Super User

Also you say "group by three years" but 17 to 20 is 4: 17, 18, 19 and 20.

 

A common way to handle such groups in use a custom format and apply the format in the procedures that are used to count things.

 

data have;
 input Age 	Users;
datalines;
17 	1
18 	2
19 	5
20 	3
21 	9
22 	9
23 	2
24 	5
25 	3
26 	2
;
proc format;
value myagegrp
17-20 = '17 to 20'
21-23 = '21 to 23'
24-26 = '24 to 26'
;
proc freq data=have;
   tables age;
   format age myagegrp.;
   weight users;
run;

A very strong advantage of using this format approach is that you can create multiple formats that are used with the same data as needed.

The groups created by proc format will be honored by report procedures like Report and Tabulate, and most graphing and analysis procedures.

Ready to join fellow brilliant minds for the SAS Hackathon?

Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.

Register today!
Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 2 replies
  • 486 views
  • 0 likes
  • 3 in conversation