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.
Registration is open! SAS is returning to Vegas for an AI and analytics experience like no other! Whether you're an executive, manager, end user or SAS partner, SAS Innovate is designed for everyone on your team. Register for just $495 by 12/31/2023.
If you are interested in speaking, there is still time to submit a session idea. More details are posted on the website.
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.