Hello,
I have 2 age variables: age_2001 and age_2020, and I want to create an age category for each in a single data step: age_2001_cat and age_2020_cat. I can do this longhand successfully, but I wanted to try it in a macro. However, when I run the macro, the final output dataset only contains the age_2020 and age_2020_cat variables. Both age_2001 and age_2001_cat variables have been overwritten. Can you please help correct my macro statement? I am using SAS 9.4. Thank you in advance!
Both times the macro runs, it creates a data set named DATASET2. So the second time you run the macro, DATASET2 overwrites the data set named DATASET2 created by the first run of the macro. You have to build into the macro the ability to change the name so it doesn't overwrite the previous data set.
Try this:
data dataset2_&age;
Although, there are much better ways to do this, maybe even without a macro — you said "I can do this longhand successfully, but I wanted to try it in a macro" but why choose a macro unless this is a learning exercise?
Anyway, here you can do this without a macro like this:
proc format;
value agef 17-19='17-19' 20-24='20-24' /* rest of age catgories here */ ;
run;
data want;
set have;
format age_2001 age_2020 agef.;
run ;
Both times the macro runs, it creates a data set named DATASET2. So the second time you run the macro, DATASET2 overwrites the data set named DATASET2 created by the first run of the macro. You have to build into the macro the ability to change the name so it doesn't overwrite the previous data set.
Try this:
data dataset2_&age;
Although, there are much better ways to do this, maybe even without a macro — you said "I can do this longhand successfully, but I wanted to try it in a macro" but why choose a macro unless this is a learning exercise?
Anyway, here you can do this without a macro like this:
proc format;
value agef 17-19='17-19' 20-24='20-24' /* rest of age catgories here */ ;
run;
data want;
set have;
format age_2001 age_2020 agef.;
run ;
@PaigeMiller Thank you, this makes sense - that dataset2 is being overwritten with the second iteration. Thank you for that helpful explanation. When I run your suggested code, I get 2 datasets, and each dataset has only 1 variable of interest, either age_2001 in one and age_2020 in the other. However, I wanted both of those variables in the same dataset. You are correct - I wanted to do the macro as a practice exercise and to save from writing out 15 extra lines of code (15 age categories for 2001 and 15 for 2020). But it sounds like skipping the macro on this is the way to go. Thank you again!
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.