Here is just the last datastep with some remarks added:
I have just noticed a typo: you created variable DEAD but used variable DIED.
I have changed it into - in bold letters - died.
data want;
set have;
length birthdead $10; /* assigning length to the new variable to create which shoulb be
in a format of: YYYY-YYYY or just YYYY */
%dt_convert(birth_x , birth); /* converting birth date from character to SAS numeric date */
%dt_convert(dead_x , died); /* converting death date from character to SAS numeric date */
if died = . then birthdead = put(year(born,4.); /* assigning result value when no death date = just birth YYYY */
else birthdead = catx('-' , year(birth), year(died)); /* assignung result as BIRTH-DEATH years: YYYY-YYYY */
/* instead CATX function yo can write: */
/* left(year(birth)) || '-' || left(year(died)) */
drop birth_x dead_x; /* dropping that variables as not needed to keep on output */
run;
data want;
set have;
length birthdead $10;
%dt_convert(birth_x , birth);
%dt_convert(dead_x , died);
if died = . then birthdead = put(year(born,4.),4.); /* sorry, my typo: correct this line: all brackest should be even)
else birthdead = catx('-' , year(birth), year(died));
drop birth_x dead_x;
Relating to your question:
Do i have to use
%macro dt_convert (dtx , dt);
if length(&dtx) = 4
then &dt = mdy(01,01,input(&dtx,4.));
else &dt = input(&dtx , mmddyy10.);
%mend dt_convert;
Above lines define a macro program.
I'm using it in order to reuse same code with different variables.
In this case convert character date given as mmddyy10. or as yyy only - into SAS numeric date.
The usage of this macro program is given as:
%dt_convert(birth_x , birth); /* create variable birth from birth_x */
%dt_convert(dead_x , died); /* create variable died from dead_x */
Macro programs are very powerfull to save time of coding and time of debugging if you use it wisely.
There is a lot to learn about SAS macro language.
My fault again. Line should be:
if dead= . then birthdead = put(year(born),4.);
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!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.