DATA Step, Macro, Functions and more

Year-variable from a date

Accepted Solution Solved
Reply
Occasional Contributor
Posts: 15
Accepted Solution

Year-variable from a date

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


Accepted Solutions
Solution
‎04-18-2016 05:58 AM
Super User
Super User
Posts: 7,970

Re: Year-variable from a date

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 /.

View solution in original post


All Replies
Trusted Advisor
Posts: 1,117

Re: Year-variable from a date

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.

 

Solution
‎04-18-2016 05:58 AM
Super User
Super User
Posts: 7,970

Re: Year-variable from a date

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 /.

Trusted Advisor
Posts: 1,117

Re: Year-variable from a date

[ Edited ]

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.

Super User
Posts: 11,343

Re: Year-variable from a date

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;

 

☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 4 replies
  • 251 views
  • 5 likes
  • 4 in conversation