I have this data set:
Obs. Indate
1 1/7/2011
2 3/7/2012
3 5/4/2014
4 1/9/2011
5 8/9/2013
6 1/1/2014
How do I create a new variable (year) which looks like this:
Obs. Year
1 2011
2 2012
3 2014
4 2011
5 2013
6 2014
Just to add, if its a character variable, then you might be better off with:
year=scan(datevar,3,"/");
If you input it to date and then take a year, you will need to handle the possiblity of missing or invalida dates. The scan will take the third piece of text delimited by /.
Hi @Gothardt,
If variable INDATE is numeric, you can define
Year=year(indate);
Otherwise, the definition could read
Year=year(input(indate, mmddyy10.));
provided that INDATE is in MM/DD/YYYY format. If it's DD/MM/YYYY format, please replace mmddyy10. by ddmmyy10. in the above code.
Just to add, if its a character variable, then you might be better off with:
year=scan(datevar,3,"/");
If you input it to date and then take a year, you will need to handle the possiblity of missing or invalida dates. The scan will take the third piece of text delimited by /.
Good point from @RW9. The SCAN technique would also be more robust in case of leading blanks
(" 1/7/2011").
Edit: By default, this would result in a character variable YEAR, whereas the approach using the YEAR function yields a numeric variable.
And depending on what you are doing, if the value is currently a SAS date value use the Year format to display as needed.
Example:
data example;
x='05APR2016'd;
run;
proc print data=have;
var x;
format x year4.;
run;
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
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.