I am trying to derive a variable based on the age in my dataset. Is there an easy way to use and apply the formats with out writing "IF" and "THEN" conditions?
Thank you for your responses.
data sas;
set sashelp.class;
length group4 $20.;
if age < 12 then do; group4= '<12 years'; group4n = 1; end;
else if 12=< age <13 then do; group4= '>=12 to <14 years'; group4n = 2; end;
else if 13=< age <14 then do; group4= '>=14 to <15 years'; group4n = 3; end;
else if age >= 14 then do; group4= '>=15 years'; group4n = 4; end;
run;
Use proc format to create a custom format, then apply it in data step with PUT function.
Eg:
proc format;
value agefmt low-12 = '<12 years'
12-13= '<14 years'
14= '<15 years'
15-high= '>=15 years';
run;
data want;
set sashelp.class;
agegroup= put(age, agefmt.);
proc print;run;
Use proc format to create a custom format, then apply it in data step with PUT function.
Eg:
proc format;
value agefmt low-12 = '<12 years'
12-13= '<14 years'
14= '<15 years'
15-high= '>=15 years';
run;
data want;
set sashelp.class;
agegroup= put(age, agefmt.);
proc print;run;
Or don't bother to create a new variable at all. Using the format from @A_Kh as an example:
Proc freq data=sashelp.class; tables age; format age agefmt. ; run;
The groups created by a custom format will be honored by reporting, analysis and generally for graphing purposes.
@A_Kh wrote:
Use proc format to create a custom format, then apply it in data step with PUT function.
Eg:
proc format; value agefmt low-12 = '<12 years' 12-13= '<14 years' 14= '<15 years' 15-high= '>=15 years'; run; data want; set sashelp.class; agegroup= put(age, agefmt.); proc print;run;
No, do NOT do this. Specifically this part:
agegroup= put(age, agefmt.);
Use a format statement to assign the agefmt. format to age.
format age agefmt.;
This not only is faster but it keeps the variable AGE as numeric, which also allows the age groups to sort in NUMERIC order. If you use the PUT statement, the values in AGEGROUP are text and will sort in alphabetical order, which is generally not what you want. You don't need variable AGEGROUP at all.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 16. Read more here about why you should contribute and what is in it for you!
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.